Selenium是一个用电脑模拟人操作浏览器网页,可以实现自动化,用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。
环境:
windows
python3.8
谷歌浏览器
安装
pip install selenium
安装驱动
以谷歌浏览器为例:
https://sites.google.com/a/chromium.org/chromedriver/downloads
地址栏输入:Chrome://version,查看浏览器版本并下载相应版本,同时我们也可以看到浏览器的安装路径,下面会用到:
解压得到一个chromedriver.exe文件,将其放置在浏览器的安装目录之下
根据上面得到路径是(“C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe”)
其他浏览器:
edge(新版,旧版):https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
火狐:https://github.com/mozilla/geckodriver/releases
实例
下面是模拟浏览器的操作,打开高德地图,获取相应城市的经纬度。
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import pyperclip #实现粘贴
city = [
'北京',
'广州',
'上海',
'乌鲁木齐'
]
data = []
browser = webdriver.Chrome("C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe")
#打开谷歌浏览器
for i in city:
browser.get("https://lbs.amap.com/console/show/picker") #打开网页
inputLocation=browser.find_element_by_xpath('//*[@id="txtSearch"]') #定位输入框
inputLocation.send_keys(i) #输入城市名称
inputLocation.send_keys(Keys.ENTER) #使用回车代替“点击搜索”
copylocation=browser.find_element_by_xpath('//*[@id="myPageTop"]/table/tbody/tr[2]/td[2]/a')
#定位复制按钮
copylocation.send_keys(Keys.ENTER)#回车复制
copylocation.click() #点击复制也是可以的
time.sleep(1) #避免操作过快,复制后暂停1秒
result = pyperclip.paste() #粘贴复制的经纬度数据
print(result) #打印出来监控数据是否正常
data.append(result) #存到列表
browser.close() #关闭浏览器
运行结果:
案例2-获取京东搜索页面后的页面代码
(1)打开浏览器
(2)找到搜索框,输入字符串,点击enter
(3)等待搜索页面显示
(4)或者页面特定内容
其中等待搜索结果显示可以通过F12查看搜索商品结果的元素是什么:这里是id=“J_main”
完整代码:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
browser = webdriver.Chrome("C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe")
try:
#打开京东首页
browser.get('https://www.jd.com')
#根据id属性id='key'查找搜索框
input = browser.find_element_by_id("key")
#发送文本
input.send_keys('python')
#按下enter键
input.send_keys(Keys.ENTER)
#创建webDriverWait对象,最长等待4秒
wait = WebDriverWait(browser,4)
#等待搜索页面显示,查找是否出现//*[@id="J_main"]/div[1]
'''Expected Conditions的使用场景有2种
直接在断言中使用
与WebDriverWait配合使用,动态等待页面上元素出现或者消失
presence_of_element_located: 判断某个元素是否被加到了dom树里,并不代表该元素一定可见
'''
locator = (By.ID,"J_main")
wait.until(ec.presence_of_all_elements_located(locator