使用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()
相关推荐
橙露4 小时前
Python 异步爬虫进阶:协程 + 代理池高效爬取实战
开发语言·爬虫·python
喵手7 小时前
Python爬虫实战:地图 POI + 行政区反查(合规接口) - 商圈热力数据准备等!
爬虫·python·爬虫实战·零基础python爬虫教学·行政区反查·地图poi·商圈热力数据准备
l1t9 小时前
DeepSeek总结的DuckDB爬虫(crawler)扩展
数据库·爬虫
喵手10 小时前
Python爬虫实战:电商问答/FAQ 语料构建 - 去重、分句、清洗,做检索语料等!
爬虫·python·爬虫实战·faq·零基础python爬虫教学·电商问答·语料构建
喵手10 小时前
Python爬虫实战:同名实体消歧 - 店铺/公司名规则合并与标准化等!
爬虫·python·爬虫实战·零基础python爬虫教学·同名实体消歧·店铺/公司名规则合并与标准化
喵手1 天前
Python爬虫实战:增量爬虫实战 - 利用 HTTP 缓存机制实现“极致减负”(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·增量爬虫·http缓存机制·极致减负
喵手1 天前
Python爬虫实战:舆情语料项目 - 从新闻抓取到文本挖掘的完整实战(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·舆论语料项目·新闻抓取到文本挖掘·爬虫实战采集舆论语料
喵手1 天前
Python爬虫实战:数据质量检测与治理 - 构建健壮的爬虫数据管道(附CSV导出 + SQLite持久化存储)!
爬虫·python·sqlite·爬虫实战·零基础python爬虫教学·数据质量检测与治理·爬虫数据管道
喵手2 天前
Python爬虫实战:电商问答语料构建完整实战 - 从爬取到检索语料的工程化实现(附CSV导出 + SQLite持久化存储)!
爬虫·python·sqlite·爬虫实战·零基础python爬虫教学·电商问答语料构建·爬取到检索语料
yq1982043011562 天前
基于Python爬虫原理的Pinterest视频资源获取技术解析与工具实践
爬虫·python·django·音视频