selenium用法总结

tech2026-02-11  2

简单示例

打开百度页面后关闭浏览器

from selenium.webdriver import Chrome chrome = Chrome() chrome.get('https://www.baidu.com/') # chrome.close() # 关闭当前页面 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}') # 更换ua chrome = Chrome(options=options) chrome.get('https://www.baidu.com/') chrome.quit()

页面元素操作

ele = chrome.find_element_by_xpath('//button[text()="提交"]') # 返回对象为一个页面元素对象 # chrome.find_elements_by_xpath('//button[text()="提交"]') # 返回对象对列表,包含多个元素对象 ele.click() # 点击页面元素 # ele.send_keys('message') # 输入框输入信息 # ele.clear() # 清空输入框中内容 # text = chrome.find_element_by_xpath('//div[@class="c-abstract"]').text # 获取元素文本 # link = chrome.find_element_by_xpath('//a').get_attribute('href') # 获取元素属性 # 设置元素属性 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.frame('frameid') chrome.switch_to.default_content() # 切换默认文档 chrome.switch_to.alert() # 切换进弹窗

页面前进,后退,刷新

chrome.forword() # 页面前进 chrome.back() # 页面后退 chrome.refresh() # 页面刷新

cookies操作

获取当前页面cookies

chrome.get_cookies() # 返回一个cookie列表

浏览器添加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")))
最新回复(0)