selenium是一个web自动化工具,它可以控制chrome浏览器实现我们想要的功能,跟爬虫不同的是:它是模拟人类的操作。

安装

下载对应版本的chromedriver

https://chromedriver.chromium.org/downloads放到PATH环境变量里, 如果是mac,可以直接执行

1
brew install chromedriver

安装python包

1
pip install selenium -i https://pypi.tuna.tsinghua.edu.cn/simple

编写脚本

获取xpath

获取xpath可以按下ctrl + shift + c点击按钮, 高亮的地方右键复制 full xpath

获取XPATH属性

获取id

Charome浏览器界面按下ctrl + shift + c 点击页面, 右边属性记录一下html的id属性

获取id属性

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/python
# -*- coding: utf-8 -*-
import time
from selenium import webdriver

# 模拟浏览器打开到gitee登录界面
driver = webdriver.Chrome()
driver.get('https://gitee.com/login')

# 将窗口最大化
driver.maximize_window()

# 通过html的id属性定位输入位置, 然后输入文本
driver.find_element(By.ID, r'user_login').send_keys("这里写你的用户名")

# 通过xpath查找位置, 然后点击鼠标
driver.find_element(By.XPATH, r'/html/body/div[2]/div[1]/div[2]/div/div/div[1]/div[2]/div/div/div[2]/div/div/div/form/div[5]/button').click()

# 退出浏览器
driver.quit()

常用操作

浏览器options参数

新版本webdriver.Chrome已经没有chromeoptions这个参数了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

import time
from selenium import webdriver
from selenium.webdriver.common.by import By

options = webdriver.ChromeOptions()


# 浏览器不自动退出。
options.add_experimental_option("detach", True)

# 隐藏浏览器界面
options.add_argument('--headless')
options.add_argument('--disable-gpu')

# 防止检测, 同时浏览器不会有受到自动化测试软件控制的提示
options.add_experimental_option('excludeSwitches', ['enable-automation'])
options.add_argument('--disable-blink-features=AutomationControlled')


driver = webdriver.Chrome(options=options)

# 防止阿里云监测
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
"source": """
Object.defineProperty(navigator, 'webdriver', {
get: () => undefined
})
"""
})

driver.get('https://signin.aliyun.com/login.htm#/main')

截图

1
driver.get_screenshot_as_file("test.png")

使用代理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from selenium import webdriver
from selenium.webdriver import ChromeOptions

options = webdriver.ChromeOptions()

# 配置代理地址
options.add_argument('--proxy-server=http://localhost:80')

# 不提示证书错误
options.add_argument("--ignore-certificate-errors")

# 让浏览器不会自动退出
options.add_experimental_option("detach", True)

driver = webdriver.Chrome(options=options)