使用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()
相关推荐
喵手6 小时前
Python爬虫实战:电商价格监控系统 - 从定时任务到历史趋势分析的完整实战(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·电商价格监控系统·从定时任务到历史趋势分析·采集结果sqlite存储
摘星|6 小时前
正则匹配与爬虫爬取图片路径综合练习
爬虫
喵手6 小时前
Python爬虫实战:京东/淘宝搜索多页爬虫实战 - 从反爬对抗到数据入库的完整工程化方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·京东淘宝页面数据采集·反爬对抗到数据入库·采集结果csv导出
0思必得07 小时前
[Web自动化] Selenium获取元素的子元素
前端·爬虫·selenium·自动化·web自动化
@zulnger9 小时前
selenium 自动化测试工具实战项目(窗口切换)
selenium·测试工具·自动化
搂着猫睡的小鱼鱼21 小时前
Ozon 商品页数据解析与提取 API
爬虫·php
深蓝电商API1 天前
住宅代理与数据中心代理在爬虫中的选择
爬虫·python
csdn_aspnet1 天前
Libvio.link爬虫技术深度解析:反爬机制破解与高效数据抓取
爬虫·反爬·libvio
0思必得01 天前
[Web自动化] Selenium处理滚动条
前端·爬虫·python·selenium·自动化
vx_biyesheji00011 天前
豆瓣电影推荐系统 | Python Django 协同过滤 Echarts可视化 深度学习 大数据 毕业设计源码
大数据·爬虫·python·深度学习·django·毕业设计·echarts