蕩漾

爱欲之人犹如执炬逆行,必有灼手之患

0%

selenium4.0更新

selenium4.0

Selenium 4 已经到来,将至少需要 Python 3.7 或更高版本。

下面介绍一下基础的语法格式

1、初始化浏览器、刷新、最大化、后退、前进、截图

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
import time
from selenium import webdriver
from selenium.webdriver.common.by import By

#初始化浏览器为谷歌浏览器
chr=webdriver.Chrome()
# 无界面的浏览器
# option = webdriver.ChromeOptions()

# option.add_argument("headless")

# chr = webdriver.Chrome(options=option)

#浏览器最大化
chr.maximize_window()

chr.get("https://www.baidu.com")

# chr.get("https://www.jd.com/")

#后退
chr.back()
#暂停2s
time.sleep(2)
#前进
chr.forward()
#刷新
chr.refresh()
#截图
chr.get_screenshot_as_file('截图.png')
#点击
chr.find_element(By.ID,'kw').click()
#输入
chr.find_element(By.ID,'kw').send_keys("saa")
time.sleep(2)
#清除输入框内容
chr.find_element(By.ID,'kw').clear()
time.sleep(2)
#关闭浏览器
chr.close()

2、单个元素定位的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
selenium4使用的时候需要导入模块    from selenium.webdriver.common.by import By

find_element(By.XPATH, "//*[@id='search']")

find_element(By.CLASS_NAME, "element_class_name")

find_element(By.ID,"element_id")

find_element(By.NAME, "element_name")

find_element(By.LINK_TEXT,"element_link_text")

find_element(By.CSS_SELECTOR, "element_css_selector")

find_element(By.TAG_NAME, "element_tag_name")

find_element(By.PARTIAL_LINK_TEXT, "element_partial_link_text")

3、多个元素定位的方法

与单个元素的定位方式类似,把find_element改成find_elements即可

4、定位select类型的下拉框

4、定位select类型的下拉框

1
2
3
4
select_by_index()           # 通过索引定位;注意:>index索引是从“0”开始。
select_by_value() # 通过value值定位,va>lue标签的属性值。
select_by_visible_text() # 通过文本值定位,即显>示在下拉框的值。
Select(chr.find_element_by_name("姓名")).select_by_index(1)

或者分开写

1
2
3
a=chr.find_element_by_name("姓名")

Select(a).select_by_index(1)

5、多窗口切换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
current_window_handle:获取当前窗口的句柄

window_handles:返回当前浏览器的所有窗口的句柄

switch_to_window():用于切换到对应的窗口

chr.get("https://www.baidu.com")
a=chr.current_window_handle
chr.execute_script('window.open()')
chr.switch_to.window(chr.window_handles[1])
chr.get("https://www.jd.com/")
# chr.switch_to.window(chr.window_handles[0])

chr.switch_to.window(a)

6、iframe切换

1
driver.switch_to.frame(driver.find_element_by_xpath("//iframe[contains(@src,'myframe')]"))

#回到默认的iframe

1
driver.switch_to.default_content()

7、键盘操作

1
2
3
4
5
6
7
8
9
send_keys(Keys.BACK_SPACE):删除键(BackSpace)

send_keys(Keys.SPACE):空格键(Space)

send_keys(Keys.TAB):制表键(TAB)

send_keys(Keys.ESCAPE):回退键(ESCAPE)

send_keys(Keys.ENTER):回车键(ENTER)
-EOF-