python&selenium一个简单的自动化测试实战:百度搜索

前提准备

  1. Chrome浏览器的安装
  2. chrome浏览器驱动地址
    http://chromedriver.storage.googleapis.com/index.html
    注意:应下载自己对应的Chrome版本,相对应版本的查看方式:
    点击如图的三个点,再点击设置
    在这里插入图片描述
    再点击关于Chrome,在方框处就可以看到Chrome的版本
    在这里插入图片描述
    3.下载chrome浏览器驱动解压到python的安装目录下面
    在这里插入图片描述
    4.安装selenium
    打开cmd,输入
pip install selenium

并且再在Pycharm
点击File–>Settings
在这里插入图片描述
选中Project下面的Python的interpreter
再点击+号
在这里插入图片描述
搜素selenium,再点击install
在这里插入图片描述

代码

PC端

#coding:utf-8
# 导包
from selenium import webdriver
import time

# 1.打开浏览器
driver = webdriver.Chrome()
time.sleep(2)

# 2.获取网址(百度)
driver.get("http://www.baidu.com")

# 3.找到输入框,通过id进行元素定位
search = driver.find_element_by_id("kw")

# 4.输入想要搜素的关键词--元素操作
search.send_keys("沙雕")
time.sleep(2)

# 找到提交按钮,元素定位
button = driver.find_element_by_id("su")
# 点击提交按钮
button.click()
time.sleep(2)

# 读取搜素结果的标题
title = driver.title
print(title)


# 断言,验证页面效果,如果不加就会直接关了
assert "hh" in title
# 关闭浏览器
driver.quit()

移动端

"""
学习目标:
    禁用浏览器的信息提示
    模拟移动端
    操作步骤
"""

# 导包
from selenium import webdriver

# 移动端的模拟
mobileEmulation={"deviceName":"iPhone X"}
chrome_options = webdriver.ChromeOptions()

# 添加实验选项  (排除交换器,开启自动化)
chrome_options.add_experimental_option("excludeSwitches",["enable-automation"])

# 添加实验选项   是否使用自动拓展功能 否
chrome_options.add_experimental_option("useAutomationExtension",False)

# 添加实验选项    移动端的模拟
chrome_options.add_experimental_option("mobileEmulation",mobileEmulation)

# 打开chrome浏览器
driver = webdriver.Chrome(options=chrome_options)
driver.get("https://www.baidu.com")

如有不足或者对以上有不明白的地方欢迎指出!

猜你喜欢

转载自blog.csdn.net/hanhanwanghaha/article/details/107658968