简单示例
打开百度页面后关闭浏览器
from selenium
.webdriver
import Chrome
chrome
= Chrome
()
chrome
.get
('https://www.baidu.com/')
chrome
.quit
()
添加配置参数
from selenium
.webdriver
import Chrome
from selenium
.webdriver
.chrome
.options
import Options
options
= Options
()
options
.add_argument
('--headless')
options
.add_argument
('--disable-gpu')
options
.add_argument
('log-level=3')
options
.add_argument
(f
'user-agent={ua}')
chrome
= Chrome
(options
=options
)
chrome
.get
('https://www.baidu.com/')
chrome
.quit
()
页面元素操作
ele
= chrome
.find_element_by_xpath
('//button[text()="提交"]')
ele
.click
()
chrome
.execute_script
('arguments[0].setAttribute(arguments[1],arguments[2])',elementobj
,attrname
,value
)
切换浏览器窗口
windows
= chrome
.window_handles
chrome
.switch_to
.window
(windows
[1])
切换iframe
chrome
.switch_to
.frame
(1)
chrome
.switch_to
.default_content
()
chrome
.switch_to
.alert
()
页面前进,后退,刷新
chrome
.forword
()
chrome
.back
()
chrome
.refresh
()
cookies操作
获取当前页面cookies
chrome
.get_cookies
()
浏览器添加cookies
for cookie
in cookies
:
chrome
.set_cookie
(cookie
)
清空所有cookies
chrome
.delete_all_cookies
selenium截屏
chrome
.save_screen_shot
('a.png')
等待页面元素出现
from selenium
.webdriver
.common
.by
import By
from selenium
.webdriver
.support
.ui
import WebDriverWait
from selenium
.webdriver
.support
import expected_conditions
as EC
WebDriverWait
(chrome
, 30).until
(EC
.presence_of_element_located
((By
.XPATH
, "//a[@id='aArticleEdt']/span")))
转载请注明原文地址:https://tech.qufami.com/read-26756.html