selenium是网页自动化测试的常用工具, 本文简述了它的安装和使用示例
配置pip3使用国内安装源
# 可以用pip3 config list查看一下相应配置项有没有
# 配置清华的源之后嗷嗷快, 人生苦短啊!
pip3 config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
使用pip3安装selenium
pip3 install selenium
# 或者MacOS推荐的python3 -m pip方式:
python3 -m pip install selenium
下载并安装对应浏览器的webdriver
官方教程:
https://www.selenium.dev/documentation/en/webdriver/driver_requirements/
以chromedriver为例:
- 下载Chrome浏览器(谷歌浏览器中国官方站点: https://www.google.cn/chrome/)
注意查看Chrome版本
, 然后下载对应主版本的chromedriver, 因为下载速度实在是太慢了! 下载地址: https://chromedriver.storage.googleapis.com/index.html- 安装webdriver到指定目录.
如果嫌这个太麻烦, 可以在调用selenium的代码中指定driver路径:), 见示例代码开头的部分
sudo mkdir -p /opt/WebDriver/bin cd !$ sudo wget https://chromedriver.storage.googleapis.com/88.0.4324.96/chromedriver_linux64.zip sudo unzip chromedriver_linux64.zip # 各个版本的webdriver都叫chromedriver, 改名并创建符号链接以便使用 sudo mv chromedriver chromedriver88 sudo ln -s chromedriver88 chromedriver export PATH=$PATH:/opt/WebDriver/bin >> ~/.profile
示例代码
这段示例代码实现的操作是:
- 打开golang.google.cn
- 找到<a>标签的文本为"Download Go"的那个链接并点击它
- 点击操作系统平台对应的下载链接
# 编辑文件
vim downloadgolang.py
# coding: utf-8
import os
import sys
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.expected_conditions import presence_of_element_located
platformPkgMap = {
"win32": "Microsoft Windows",
"darwin": "Apple macOS",
"linux": "Linux",
}
pkg = platformPkgMap.get(sys.platform, "Source")
#DRIVER_PATH = "~/chromedriver88"
#with webdriver.Chrome(executable_path=DRIVER_PATH) as driver:
#This example requires Selenium WebDriver 3.13 or newer
with webdriver.Chrome() as driver:
wait = WebDriverWait(driver, 10)
driver.get("http://golang.google.cn")
time.sleep(3)
driver.find_element(By.LINK_TEXT, "Download Go").click()
#driver.find_element(By.NAME, "q").send_keys("" + Keys.RETURN)
downloadBoxes = driver.find_elements(By.CSS_SELECTOR, "div.platform")
for d in downloadBoxes:
print(d.text)
if pkg == d.text:
d.click()
time.sleep(10)
break
print(downloadBoxes)
#first_result = wait.until(presence_of_element_located((By.CSS_SELECTOR, "h3>div")))
#print(first_result.get_attribute("textContent"))
# 运行
python3 downloadgolang.py
selenium文档
https://www.selenium.dev/documentation/en/
https://selenium-python.readthedocs.io/ 如果使用python, 这个更细致, 还有中文版的