selenium用法总结

简单示例

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

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值