Selenium基本操作

环境准备

pip install selenium
下载对应版本的谷歌浏览器驱动chromedriver,放在Python目录的Scripts文件夹下

基本使用

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
34
35
36
37
38
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
from selenium.webdriver import ChromeOptions
from time import sleep
from PIL import Image

#实例化一个浏览器对象
bro = webdriver.Chrome()

#发起请求
bro.get("https://www.baidu.com")

#定位所用的方法By.XPATH By.CSS_SELECTOR By.ID
#定位输入框并写入字符
kw = bro.find_element(By.ID, "kw")
kw.send_keys("Hello")
sleep(2)

#定位提交按钮并点击
su = bro.find_element(By.ID, "su")
su.click()
sleep(2)

#执行js程序(向下滚动一个屏幕)
bro.execute_script('window.scrollTo(0, document.body.scrollHeight)')
sleep(2)

#回退到下一个界面
bro.back()
sleep(2)

#进入下一个页面
bro.forward()
sleep(2)

#退出
bro.quit()

如果定位的标签在iframe标签中,需要切换作用域
bro.switch_to.frame(iframe_id)

动作链

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#点击某个坐标上的元素
ActionChains(bro).move_to_element_with_offset(坐标).click().perform()

# 慢慢拖动某个元素
x = 17, y = 0
action = ActionChains(bro)
action.click_and_hold(su)
for i in range(5):
#perform立即执行
action.move_by_offset(x, y).perform()
sleep(0.3)

#释放
aciton.release()

实现对某个页面中的目标元素进行截图保存

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
34
35
36
37
38
39
40
41
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
from selenium.webdriver import ChromeOptions
from time import sleep
from PIL import Image
import os

# 获取桌面路径
desktop_path = os.path.join(os.path.expanduser('~'), 'Desktop')
# 切换工作目录到桌面
os.chdir(desktop_path)

#当前电脑缩放比例
computer_scale = 1.25
options = ChromeOptions()

#规避检测
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_argument("--disable-blink-features=AutomationControlled")

#实现无头浏览器(无可视化界面)
#options.add_argument("--headless")
#options.add_argument("--disable-gpu")

bro = webdriver.Chrome(options=options)
bro.get("https://www.baidu.com/")

#对整张页面截图
bro.save_screenshot("test.png")
#获取目标元素的位置 location:左上角位置 size:宽高
input = bro.find_element(By.ID, "kw")
location = input.location
size = input.size

img = Image.open("test.png")
#需要根据电脑缩放比例定位裁剪
img = img.crop((location["x"] * computer_scale, location["y"] * computer_scale, (location["x"] + size["width"]) * computer_scale, (location["y"] + size["height"]) * computer_scale))
img.save("test.png")

bro.quit()

找到输入框输入python并回车

1
2
from selenium.webdriver.common.keys import Keys
bro.find_element(By.XPATH, '//*[@id="search_input"]').send_keys("python", Keys.ENTER)

切换窗口为窗口列表的最后一个

1
bro.switch_to.window(bro.window_handles[-1])

等待

1
2
3
4
5
6
7
8
9
from selenium.webdriver.support.wait import WebDriverWait
from selenium import webdriver

bro = webdriver.Chrome()
# 最多等待10秒
wait = WebDriverWait(bro, 10)
bro.get('https://www.baidu.com')
# 等待id为u1的元素出现
wait.until(lambda x: x.find_element_by_xpath('//*[@id="u1"]'))