0


python selenium4 EdgeDriver动态页面爬取

截止至2024.7.16

chrome浏览器最新版本为126.0.6478.127

但对应的chromeDriver版本都低于此版本,因此,转用Edge浏览器

说明:仅记录自己使用过程中用到的一些代码和感受,看具体情况不定期更新。

selenium官方文档

1、安装selenium及下载EdgeDriver

pip install selenium

edgeDriver下载地址

2、在环境变量的path中,放入EdgeDriver的路径

3、抓取

  1. import random
  2. from selenium import webdriver
  3. from selenium.webdriver.common.by import By
  4. USER_AGENT_LIST = [
  5. 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/530.6 (KHTML, like Gecko) Chrome/2.0.174.0 Safari/530.6',
  6. 'Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/0.3.154.6 Safari/525.19',
  7. 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.13 (KHTML, like Gecko) Chrome/9.0.599.0 Safari/534.13',
  8. 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/534.8 (KHTML, like Gecko) Chrome/7.0.521.0 Safari/534.8',
  9. 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1b2pre) Gecko/20081015 Fennec/1.0a1',
  10. 'Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5'
  11. ]
  12. def user_agent():
  13. return random.choice(USER_AGENT_LIST)
  14. url ='待爬网址'
  15. edge_options = webdriver.EdgeOptions()
  16. edge_options.use_chromium = True # 指定使用基于Chromium的Edge浏览器
  17. edge_options.add_argument("headless") # 无界面模式
  18. edge_options.add_argument("disable-gpu") # 禁用GPU加速
  19. #因为是遍历查询,所以加入了随机user-agent
  20. edge_options.add_argument("user-agent="+user_agent())
  21. driver = webdriver.Edge(options=edge_options)
  22. driver.get(url)

4、常用代码

1、查找elements(这返回的是数组,如果确定唯一的,则用find_element)

  1. links = driver.find_elements(By.XPATH,'//div[@class="jbxx-content"]//a')

注:语法跟xpath相似

2、获取WebElement的属性值

  1. cos = link.get_attribute("href")

3、执行click事件

  1. #如果报ElementClickInterceptedException错误的话
  2. driver.execute_script("arguments[0].scrollIntoView();",link)
  3. #执行点击事件
  4. link.click()

4、获取text值

  1. text = driver.find_element(By.ID, "justanotherlink").text

本文转载自: https://blog.csdn.net/yangjiaosun/article/details/140468705
版权归原作者 杨兜兜 所有, 如有侵权,请联系我们删除。

“python selenium4 EdgeDriver动态页面爬取”的评论:

还没有评论