9.自动化测试工具selenium

9.自动化测试工具selenium

明廷盛 嘻嘻😁

第一章 环境配置

第一节 安装selenium

1
pip install selenium==4.9.1

第二节 下载浏览器(Chrome)驱动

不是所有的浏览器都需要驱动才能, 用selenium去操作, 有些比如IE可以直接操作, 这里我们就用最好用,也最常用的Chrome浏览器来演示

STEP1: 先把浏览器更新到最新

STEP2: 下载浏览器驱动

网址选Stable=>chromedriver win64
Pasted image 20250115140141|450

STEP3: 解压=>把exe文件拖到要使用的代码目录

Pasted image 20250115140336|346

第二章 Selenium基本使用

第一节 Hello Selenium

  • $ 引导: 先说下 Selenium这个包干什么的, 方便你去理解编程; 这包是我们爬虫的”杀手锏”, 当我们的requests包实在爬不了的时候, 我们可以直接通过selenium去操作浏览器, 操作你Chrome, IE, Firefox…….所以, selenium就是用python代码操作浏览器的

STEP1: 获取service对象

STEP2: 获取浏览器对象

STEP3: 访问 指定网址

Chrome:打开就关,python程序结束,Chrome自己就关; 解决方法:sleep() or 用 Firefox

STEP4: Sleep+ 手动关闭浏览器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import time

from selenium import webdriver
from selenium.webdriver.chrome.service import Service

# STEP1: 获取service对象
service = Service(executable_path="./browser_driver/chromedriver.exe")

# STEP2: 获取浏览器对象(因为selenium就是用来操作浏览器的, 所以要获取浏览器对象)
browser = webdriver.Chrome(service=service)

# STEP3: 访问 指定网址 [Chrome:打开就关,python程序结束,Chrome自己就关; 解决方法:sleep() or 用 Firefox]
aim_url = "https://www.baidu.com"
browser.get(aim_url)

# STEP4: 代码休眠 + 手动关闭浏览器
time.sleep(30) # 代码休眠
browser.quit() # 手动关闭浏览器

第二节 browser对象常用方法

序号方法描述示例代码
get()模拟访问目标网址browser.get(“https://www.baidu.com“)
page_source获取网页源代码(HTML)code = `browser.page_source
get_cookies()获取当前页面的cookiecookie = browser.get_cookies()
get_screenshot_as_file()截取当前页面的屏幕截图,保存为文件browser.get_screenshot_as_file(“123.png”)
current_url获取当前请求的页面网址current_url = browser.current_url
add_cookie(dict类型)添加cookie只能逐个去添加
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
42
# =================================
# @Time : 2025年01月15日
# @Author : 明廷盛
# @File : 3.browser常用方法.py
# @Software: PyCharm
# @ProjectBackground:
# =================================

from selenium import webdriver
from selenium.webdriver.chrome.service import Service

# STEP1:获取service对象
service = Service(executable_path="./browser_driver/chromedriver.exe")
# STEP2:获取浏览器对象
browser = webdriver.Chrome(service=service)

# STEP3:模拟访问目标地址
browser.get("https://www.baidu.com")

"""browser常用方法"""
# 1.获取网页源代码(HTML) [有什么用? 转为etree对象, 直接用xpath]
code = browser.page_source.encode("utf-8") # 也可直接.page_source, 不用encode, 如果encode, 获取内容必须decode
# print(code.decode())

# 2.获取cookie
cookie = browser.get_cookies()


# 3.页面截图(不能有文件夹,直接写图片名称,默认是当前目录下生产图片)
browser.get_screenshot_as_file("123.png")

# 4.获取请求的页面网址
current_url = browser.current_url

# 5.添加cookie
cookie_dict = {
"VipRUID": "617454137",
"VipRNAME": "19037916824",
}
# 逐个添加cookie
for name, value in cookie_dict.items():
browser.add_cookie({"name": name, "value": value})

第三节 使用代理IP❗❗❗

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
"""
* 解决方法: https://blog.csdn.net/qq_35578171/article/details/135346389
* 插件GitHUb: https://github.com/RobinDev/Selenium-Chrome-HTTP-Private-Proxy
"""

import requests
from selenium import webdriver
from selenium.webdriver.chrome.service import Service


API_URL = "https://dps.kdlapi.com/api/getdps/?secret_id=o5b3w54kddfiskjsu5ta&signature=tr45ga5grnvp1943h0paert5qwquy7cb&num=1&pt=1&sep=1"
USERNAME = "d4472377283"
PASSWORD = "rudm2ozb"
BROWSER_EXTENSION_PATH = r"D:\ins\browser_driver\chromedriver.exe"
EXTENSION_PATH = r"D:\ins\Selenium-Chrome-HTTP-Private-Proxy-master"


def get_proxy_details():
response = requests.get(API_URL)
proxy_ip = response.text.strip()
host, port = proxy_ip.split(":")
return host, port


def create_background_js(host, port):
content = f"""
var config = {{
mode: "fixed_servers",
rules: {{
singleProxy: {{
scheme: "http",
host: "{host}",
port: parseInt({port})
}},
bypassList: ["localhost"]
}}
}};

chrome.proxy.settings.set({{value: config, scope: "regular"}}, function() {{}});

function callbackFn(details) {{
return {{
authCredentials: {{
username: "{USERNAME}",
password: "{PASSWORD}"
}}
}};
}}

chrome.webRequest.onAuthRequired.addListener(
callbackFn,
{{urls: ["<all_urls>"]}},
['blocking']
);
"""
with open(fr"{EXTENSION_PATH}\background.js", "w") as file:
file.write(content)


def launch_browser():
proxy_ip_host, proxy_ip_port = get_proxy_details() # 获取代理ip的host和prot
create_background_js(proxy_ip_host, proxy_ip_port) # 改写插件的background.js文件
service = Service(executable_path=BROWSER_EXTENSION_PATH)
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless=new") # 无头模式(新版)
chrome_options.add_argument(f'--load-extension={EXTENSION_PATH}') # 加载浏览器拓展

browser = webdriver.Chrome(service=service, options=chrome_options)
browser.get('http://httpbin.org/ip')
print(browser.page_source)
browser.quit()


if __name__ == '__main__':
launch_browser()

第四节 作业

需求: 使用python在百度的①搜索框中输入内容 ②点击”百度一下”Pasted image 20250115195818|96

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
# =================================
# @Time : 2025年01月15日
# @Author : 明廷盛
# @File : 2.模拟发送百度搜索请求.py
# @Software: PyCharm
# @ProjectBackground: 需求: 使用python在[百度](https://www.baidu.com)的①搜索框中输入内容 ②点击"百度一下"
# =================================
import time

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By # 获取页面元素的包

# STEP1: 获取service对象
service = Service(executable_path="./browser_driver/chromedriver.exe")

# STEP2: 获取"浏览器"对象
browser = webdriver.Chrome(service=service)

"整体流程: ①打开百度==>②获取搜索框元素+向搜索框中填充元素==>③获取'百度一下'按钮元素+模拟点击"
# ①打开百度
aim_url = "https://www.baidu.com"
browser.get(aim_url)

# ②获取搜索框元素+向搜索框中填充元素
search_element = browser.find_element(By.CSS_SELECTOR, "#kw") # 使用"CSS选择器"选择搜索框的id [需要#号]
search_element.send_keys("python") # 填充搜索内容

# ③获取'百度一下'按钮元素+模拟点击"
button = browser.find_element(By.ID, "su") # 可以直接通过ID, 但不用加#号
button.click() # 模拟点击

# STEP3: sleep+关闭
time.sleep(10)
browser.close()

第三章 参数配置

第一节 常见配置参数一览

  • $ 语法: 通过webdriver.ChromeOptions()获取'selenium.webdriver.chrome.options.Options对象
序号参数配置用途示例
==1==prefs静止加载图片prefs = {"profile.managed_default_content_settings.images": 2}
2add_argument('-headless')无头模式(不显示浏览器界面)options.add_argument('-headless')
3add_argument('user-agent')设置请求头options.add_argument('user-agent=这是请求头的内容')
4useAutomationExtension去除”开发者警告”options.add_experimental_option('useAutomationExtension', False)
5excludeSwitches去除”开发者警告”options.add_experimental_option('excludeSwitches', ['enable-automation'])
==6==add_argument('--proxy-server')设置代理访问options.add_argument('--proxy-server=http://58.30.184:9091')
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
42
43
44
45
# =================================
# @Time : 2025年01月15日
# @Author : 明廷盛
# @File : 3.selenium参数配置.py
# @Software: PyCharm
# @ProjectBackground:
# =================================
import time

from selenium import webdriver
from selenium.webdriver.chrome.service import Service

# STEP1:获取service对象
service = Service(executable_path="./browser_driver/chromedriver.exe")

# STEP`1.5`: 参数配置
options = webdriver.ChromeOptions() # 获取Options()对象

# [常用] 1.静止加载图片
prefs = {"profile.managed_default_content_settings.images": 2}
options.add_experimental_option("prefs", prefs)

# 2.无头模式(不显示浏览器[但还是会执行],最剩内存+性能)
# options.add_argument(f'-headless')

# 3.请求头设置
# options.add_argument(f'user-agent={"这是请求头的内容"}')

# 4.去除"开发者警告"
options.add_experimental_option('useAutomationExtension', False)
options.add_experimental_option('excludeSwitches', ['enable-automation'])

# [常用] 5.设置代理访问
# options.add_argument("--proxy-server=http://58.30.184:9091")


# STEP2:获取浏览器对象
browser = webdriver.Chrome(service=service, options=options)

# STEP3:访问指定网址
browser.get("https://www.baidu.com")

# STEP4:sleep+quit
time.sleep(50)
browser.quit()

第四章 页面元素获取

第一节 获取单个页面元素

  • $ 语法: By包+browser.find_element()
1
2
3
4
5
6
from selenium.webdriver.common.by import By

# 获取单个页面元素
browser.find_element(By.ID, 'wp') # 和CSS不同是, 不需要加#号
browser.find_element(By.CSS_SELECTOR, '#wp') # CSS选择器怎么写, 这就怎么写
browser.find_element(By.XPATH, r'\\ul[@class="ul_style"]\\li') # 用XPath提取, xpath写后面即可

第二节 获取多个页面元素

  • $ 语法: By包+browser.find_elements()

需求: 获取 长沙晚报网 所有的<li>标签的

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
# =================================
# @Time : 2025年01月15日
# @Author : 明廷盛
# @File : 6.作业(获取多个页面元素).py
# @Software: PyCharm
# @ProjectBackground:
# =================================


from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

service = Service(executable_path="./browser_driver/chromedriver.exe")
browser = webdriver.Chrome(service=service)

aim_url = "https://www.icswb.com/channel-list-channel-161.html"
browser.get(aim_url)

# 获取ul下的所有li标签
li_list = browser.find_elements(By.CSS_SELECTOR, "#NewsListContainer li")
[print(i) for i in li_list]

"""
题外话:这里主要是想展示elements的用法,真想获取页面元素的文本内容的话
selenium做不到! selenium做不到! selenium做不到!
selenium做不到! selenium做不到! selenium做不到!
selenium做不到! selenium做不到! selenium做不到! (做的不是很好, 可以说很差劲...)
可以同获取 browser.get_source() 页面HTML原码, 解析为lxml.etree再用xpath去获取文本
"""

第五章 元素属性获取

  • $ 语法: 元素.get_attribute("属性名")

    需求: 获取 长沙晚报网 所有的<li>标签的下的<a>的链接href和标题title属性

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
# =================================
# @Time : 2025年01月15日
# @Author : 明廷盛
# @File : 7.获取元素属性.py
# @Software: PyCharm
# @ProjectBackground: 需求: 获取 [长沙晚报网](https://www.icswb.com/channel-list-channel-161.html) 所有的`<li>`标签的下的`<a>`的链接href和标题title属性
# =================================
import time

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

service = Service(executable_path="./browser_driver/chromedriver.exe")
browser = webdriver.Chrome(service=service)

browser.get("https://www.icswb.com/channel-list-channel-161.html")

# 获取页面元素
a_list = browser.find_elements(By.CSS_SELECTOR, "#NewsListContainer li a")

# 获取元素内容
for a in a_list:
href = a.get_attribute('href')
title = a.get_attribute('title')
print(href, title) # 会有重复的, 选这个网址作为示例不太好

第六章 元素交互

第一节 常用的交互方法

6.1.1 填充属性值

  • $ 语法: 元素.send_keys("值")

6.1.2 清空值

  • $ 语法: 元素.clear()

6.1.3 模拟点击

  • $ 语法: 元素.click()

6.1.4 iframe切换

  • $ 语法: browser.switch_to.frame("子页面元素")
  • & 说明: 页面HTML,是会存在”嵌套关系”的(如导航栏多个页面公用, 直接嵌套)
  • ! 注意: 嵌套是不可通过xpath的//语法直接获取到的, 必须得切换到目标iframe中才能继续使用//语法
    Pasted image 20250116100456|800

    需求: 登录 豆瓣 自动输入账号信息, 和密码信息, 点击”登录”进行登录

ins
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
# =================================
# @Time : 2025年01月16日
# @Author : 明廷盛
# @File : 8.iframe切换(豆瓣登录).py
# @Software: PyCharm
# @ProjectBackground: > 需求: 登录 [豆瓣](https://www.douban.com/) 自动输入账号信息, 和密码信息;(输入即可,无需登录)
# =================================
import time

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

service = Service(executable_path="./browser_driver/chromedriver.exe")
browser = webdriver.Chrome(service=service)

aim_url = "https://www.douban.com/"
browser.get(aim_url)

# 获取到iframe元素
login_iframe = browser.find_element(By.XPATH, '//div[@class="login"]/iframe')
"""print(login_iframe.get_attribute("style")) # 一定要打印下属性确定下, 看有没有拿错"""

# 切换到iframe中
browser.switch_to.frame(login_iframe)

# 获取iframe中的目标元素
# 需求步骤1:切换到密码登录
time.sleep(2)
browser.find_element(By.CLASS_NAME, "account-tab-account").click() # 模拟点击切换

# 需求步骤2:获取"用户名"和"密码"登录框
account_input = browser.find_element(By.ID, "username")
password_input = browser.find_element(By.ID, "password")

# 需求步骤3:填充内容
account_input.send_keys("这是用户名")
password_input.send_keys("我是password")

time.sleep(2)
browser.quit()

第二节 动作链

  • @ 解释: 什么是动作链, 比如”拖拽元素A到元素B内”, 这就是一个动作链 (滑动验证码常用)
  • $ 语法:
    • 包: from selenium.webdriver import ActionChains
    • 步骤: ①创建ActionChains(browser)对象 ②编写动作链内容 ③执行动作链action.perform()

需求: 拖拽 页面 元素

ins
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
import time

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains # "动作链"包

service = Service(executable_path="./browser_driver/chromedriver.exe")
browser = webdriver.Chrome(service=service)

aim_url = "https://www.runoob.com/try/try.php?filename=jqueryui-api-droppable"
browser.get(aim_url)

# 需求步骤1:切换到iframe中
targ_iframe = browser.find_element(By.XPATH, '//div[@id="iframewrapper"]/iframe')
browser.switch_to.frame(targ_iframe)

# 需求步骤2:获取"源元素"和"目标位置元素"
source = browser.find_element(By.ID, "draggable")
target = browser.find_element(By.ID, "droppable")

# 需求步骤3:创建"动作链"
action = ActionChains(browser) # STEP1:创建动作链对象
action.drag_and_drop(source, target) # STEP2:编辑动作链内容
action.perform() # STEP3:执行动作链

time.sleep(10)
browser.quit()

第三节 页面滚动(如何执行js代码)

  • $ 执行js代码的的语法: browser.execute_script("js代码")
  • $ js滚动页面的语法:
    • window.scrollBy(X,Y):相对滚动:每次以当前位置为起点,向下滚动”dist*50”的距离,越滚越多
    • window.scrollTO(X,Y):绝对滚动:每次以当前位置为起点,向下滚动”dist*50”的距离,越滚越多

      需求: 向下滚动这个页面页面

ins
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import time

from selenium import webdriver
from selenium.webdriver.chrome.service import Service

service = Service(executable_path="./browser_driver/chromedriver.exe")
browser = webdriver.Chrome(service=service)

aim_url = "https://36kr.com/"
browser.get(aim_url)

# 开始执行js代码,滚动页面
for dist in range(1, 30):
browser.execute_script(f"window.scrollBy(0, {dist * 50})") # 相对滚动:每次以当前位置为起点,向下滚动dist*50的距离,[越滚越多]
# browser.execute_script(f"window.scrollTo(0,{dist * 50})") # 绝对滚动:每次以0,向下滚动dist*50的距离,[每次滚动距离一致]
time.sleep(0.5)

time.sleep(20)
browser.quit()

第四节 切换浏览器选项卡

Pasted image 20250116231135

第七章 绕过检测

谷歌浏览器: 通过访问这个网站可以判断, 当前是否通过webdriver进行访问的; 或在”控制台”: navigator.webdriver false/true
Pasted image 20250116231219|350Pasted image 20250116231228|325

  • 这里介绍谷歌浏览器绕过检测的方法: 配置--disable-blink-features=AutomationControlled
  • 火狐要写插件教程, 这里不赘述
    Pasted image 20250116231256|725

第八章 作业(综合案例)

需求: 爬取 苏宁易购 ①搜索商品 ②抓取商品信息(商品名称, 价格, 链接)

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# =================================
# @Time : 2025年01月16日
# @Author : 明廷盛
# @File : 11.作业(爬取苏宁易购商品信息).py
# @Software: PyCharm
# @ProjectBackground: 需求: 爬取 [苏宁易购](https://www.suning.com/?safp=d488778a.13701.0.efacd7b69d&safpn=10007) ①搜索商品 ②抓取商品信息(商品名称, 价格, 链接)
# =================================
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import pymongo
import time
from random import randint
from lxml import etree


class SuningShop:
# 数据库
mongo_client = pymongo.MongoClient()
collection = mongo_client["py_spider"]['suning_shop']

# selenium
service = Service(executable_path="./browser_driver/chromedriver.exe")
options = webdriver.ChromeOptions() # 获取selenium配置对象
# 配置1:静止图片加载
prefs = {"profile.managed_default_content_settings.images": 2}
options.add_experimental_option("prefs", prefs)
# 配置2:去除开发者警告
options.add_experimental_option('useAutomationExtension', False)
options.add_experimental_option('excludeSwitches', ['enable-automation'])
# 浏览器对象
browser = webdriver.Chrome(service=service, options=options)
# 目标网址
aim_url = "https://www.suning.com/?safp=d488778a.13701.0.efacd7b69d&safpn=10007"

# 模拟"输入搜索内容"并"点击搜索"
@classmethod
def input_search(cls, content):
cls.browser.get(cls.aim_url)
# 获取"搜索框"和"搜索按钮"
search_input = cls.browser.find_element(By.ID, "searchKeywords")
search_button = cls.browser.find_element(By.ID, "searchSubmit")
# 输入搜索内容+点击搜索按钮
time.sleep(2)
search_input.send_keys(content)
search_button.click()
time.sleep(2)

# 模拟页面向下滚动
@classmethod
def scroll_page(cls):
for dist in range(30):
cls.browser.execute_script(f"window.scrollTo(0, {700 * dist})")
time.sleep(randint(1, 3))

# 获取当前页面的数据
@classmethod
def get_cur_page_information(cls):
html_obj = etree.HTML(cls.browser.page_source)
commodity_list = html_obj.xpath('//ul[@class="general clearfix"]/li') # 商品列表
time.sleep(3)
for commodity in commodity_list:
data = dict()
price = commodity.xpath('.//div[@class="price-box"]/span[@class="def-price"]/text()')
data['price'] = price[1] if len(price) >= 2 else price[0]
url = commodity.xpath('.//div[@class="title-selling-point"]/a/@href')[0]
data['url'] = "https://passport.suning.com" + url[1:] if "http" not in url else url
title = commodity.xpath('.//div[@class="title-selling-point"]/a//text()')[0]
data["title"] = "".join([t for t in title if t!="/n"])
print(data)
print("============================")
cls.collection.insert_one(data)

# 启动函数,
@classmethod
def launch(cls, content):
cls.input_search(content)
time.sleep(2)
cls.scroll_page()
time.sleep(3)
cls.get_cur_page_information()
time.sleep(3000)
print("done!")
cls.browser.quit()


if __name__ == '__main__':
sunning_shop = SuningShop()
sunning_shop.launch("电脑")

第X章 总结

第一节 包

序号描述示例
基础包a) from selenium import webdriver b)from selenium.webdriver.chrome.service import Service
元素获取from selenium.webdriver.common.by import By
动作链from selenium.webdriver import ActionChains

第二节 Browser常用方法

序号方法返回值描述示例代码
get()模拟访问目标网址browser.get(“https://www.baidu.com“)
page_sourcestr获取网页源代码(HTML)code = `browser.page_source
get_cookies()list<dict>获取当前页面的cookiecookie = browser.get_cookies()
get_screenshot_as_file()bool截取当前页面的屏幕截图,保存为文件browser.get_screenshot_as_file(“123.png”)
current_urlstr获取当前请求的页面网址current_url = browser.current_url
add_cookie(dict)一次只能加一个字典cookie

第三节 参数配置:

序号参数配置描述示例
==①==prefs静止加载图片prefs = {"profile.managed_default_content_settings.images": 2}
add_argument('-headless')无头模式(不显示浏览器界面)options.add_argument('-headless')
add_argument('user-agent')设置请求头options.add_argument('user-agent=这是请求头的内容')
useAutomationExtension去除”开发者警告”options.add_experimental_option('useAutomationExtension', False)
excludeSwitches去除”开发者警告”options.add_experimental_option('excludeSwitches', ['enable-automation'])
==⑥==add_argument('--proxy-server')设置代理访问options.add_argument('--proxy-server=http://58.30.184:9091')

第四节 元素获取方法 By包

用途示例
选取一个元素browser.find_element(By.ID, 'wp')
选取多个元素li_list = browser.find_elements(By.CSS_SELECTOR, "ul li")

第五节 元素属性获取:

  • $ 语法: 元素.get_attribute("属性名")

第六节 元素交互: ActionChains包

序号方法描述
元素.send_keys("值")填充属性值
元素.clear()清除内容
元素.click()元素点击
browser.switch_to.frame("子页面元素")切换iframe
browser.execute_script("js代码")执行JS代码
action.drag_and_drop(source, target)动作链
序号方法返回值
browser.find_element()selenium.webdriver.remote.webelement.WebElement
browser.find_elements()list
title
1
2
3
4
5
from selenium.webdriver.common.by import By

browser.find_element(By.ID, 'wp') # 和CSS不同是, 不需要加#号
browser.find_element(By.CSS_SELECTOR, '#wp') # CSS选择器怎么写, 这就怎么写
browser.find_element(By.XPATH, r'\\ul[@class="ul_style"]\\li') # 用XPath提取, xpath写后面即可
  • Title: 9.自动化测试工具selenium
  • Author: 明廷盛
  • Created at : 2025-02-15 14:34:49
  • Updated at : 2025-02-09 15:59:00
  • Link: https://blog.20040424.xyz/2025/02/15/🐍爬虫工程师/第一部分 爬虫基础/9.自动化测试工具selenium/
  • License: All Rights Reserved © 明廷盛