使用selenium实现对页面元素的抓取

一、背景介绍

工作中有个需求是需要对某个页面进行监控,但由于要监控页面数据是异步加载的,因此很难从状态码和返回结果层面进行校验。于是乎想到了通过判断页面元素是否存在且显示内容是否正确来达到此目标。调研了一下发现selenium可以实现对这种动态数据加载页面的抓取

二、数据异步加载页面的监控方式

备注:我采用的是方法一

  • 方法一:使用selenium对异步加载后的页面元素进行抓取
  • 方法二:使用requests库直接对异步加载的接口进行请求

二、环境准备

注意:浏览器版本与对应驱动版本必须一致

  • Chrome浏览器版本:Chromium 77.0.3844.0
  • chromedriver版本:77.0.3844.0
  • selenium版本:4.9.1
  • Python3

三、具体代码

复制代码
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager

url = "http://mock.test.com"
chrome_options = webdriver.ChromeOptions()   # 貌似从selenium 4.6以上就不用明确指定驱动版本啦
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument('--disable-extensions')
chrome_options.add_argument("--headless")
chrome_options.add_experimental_option("detach", True)

driver = webdriver.Chrome(options=chrome_options)
driver.get(url)   # 本行用于访问指定的地址

# 等待指定元素出现,最多等待10秒
element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPATH, '//*[@id="xxx"]/div[1]/h2'))
)
                    
title = driver.find_element(By.XPATH, '//*[@id="xxx"]/div[1]/h2').text
productname = driver.find_element(By.XPATH, '//*[@id="xxx"]/div[2]/div[1]/ul/li/span[1]').text

print("title:", title)
print("product name:", productname)

assert title == "是标题啊"
assert productname == "是名字呀"

# 关闭浏览器
driver.quit()
相关推荐
电商API_180079052479 小时前
Python 实现闲鱼商品列表批量采集,接口异常重试机制搭建
大数据·开发语言·数据库·爬虫·python
绘梨衣54712 小时前
采集基类设计遇到的描述符bug
爬虫·python·bug
如烟花的信页16 小时前
*花顺cookie逆向分析
javascript·爬虫·python·js逆向
qq36219670516 小时前
Telegram APK 下载安装完整指南 — 2026年最新
android·人工智能·爬虫·chatgpt·智能手机
yijianace17 小时前
Python爬虫项目实战:从 BeautifulSoup 到 XPath
爬虫·python·beautifulsoup
金融RPA机器人丨实在智能18 小时前
工程线索工具合规避坑指南:使用开源爬虫抓取数据会触犯法规吗?实在Agent给出了安全答案
人工智能·爬虫·安全·ai·开源
去码头整点薯条ing18 小时前
某红书笔记接口逆向【x-s参数】
javascript·爬虫·python
在放️18 小时前
Python 爬虫 · XML、xpath 与 lxml 模块基础
开发语言·爬虫·python
小白学大数据19 小时前
知网数据实战:爬虫 + 网络分析打造论文关键词图谱
爬虫·python·scrapy
有味道的男人19 小时前
利用爬虫获取 1688 商品详情:高效采集完整方案(含原生爬虫风险 + Open Claw 合规替代方案
爬虫