Python selenium译文学习博客地址
https://www.cnblogs.com/taceywong/p/6602927.html?utm_source=tuicool&utm_medium=referral
一.1.下载并安装python3,在安装时选择添加add to path可以自动配置环境变量,安装成功后,在cmd窗口输入python查看,成功安装后提示python版本
https://www.python.org/downloads/
下载selenium-3.13.0.tar.gz解压到python3的目录下
https://pypi.org/project/selenium/#files
2.下载浏览器webdriver的驱动器并解压在python3目录下
| Chrome: | https://sites.google.com/a/chromium.org/chromedriver/downloads |
| Edge: | https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/ |
| Firefox: | https://github.com/mozilla/geckodriver/releases |
| Safari: | https://webkit.org/blog/6900/webdriver-support-in-safari-10/ |
安装selenium :pip install selenium
测试例子:
例1:实现打开百度网站并搜索selenium
# coding = utf-8
from selenium import webdriver
browser = webdriver.Firefox()
browser.get("http://www.baidu.com")
browser.find_element_by_id("kw").send_keys("selenium") #F12查看到的www.baidu.com的输入框的Id是“kw”,通过id找到该元素后,输入“selenium”字符串
browser.find_element_by_id("su").click() #F12查看到的www.baidu.com的submit的Id是“su”,通过id找到该元素后,执行点击事件
browser.quit()
例2:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Firefox()
driver.get("http://www.python.org") #打开浏览器并输入网址打开该网站
assert "Python" in driver.title
'''1.assert 是断言函数,用于判断逗号前面的表达式是否为true,
2.表达式“"Python" in driver.title”如果为ture,就继续执行脚本,若是为false就中断执行脚本并抛出异常,
3.逗号后面的字符串是自定义的异常信息,若是没有自定义则抛出信息“ assert "Python111" in driver.title AssertionError”,
若是自定义了字符串就抛出该字符串并中断执行脚本
'''
elem = driver.find_element_by_id("id-search-field") #通过webdriver中id的方式定位html中的输入框元素
elem.clear()
elem.send_keys("测试") #向找到的输入框中输入文本“测试”
elem.send_keys(Keys.RETURN) #调用键盘上的回车键
time.sleep(5) #让脚本暂停,5s后再执行脚本
assert "No results found." not in driver.page_source,"没有搜索到对应的结果" #driver.page_source查看当前网页的源代码
#print(driver.page_source) #打印输出当前html网页
time.sleep(10)
driver.close() #close关闭当前页签,若是只有一个页签就关闭浏览器。driver.quit()关闭浏览器
遇到问题:assert "No results found." not in driver.page_source中driver.page_source获得的html文件不是当前搜索成功后的页面,用driver.time()解决