使用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()
相关推荐
AC赳赳老秦3 小时前
Prometheus + DeepSeek:自动生成巡检脚本与告警规则配置实战
前端·javascript·爬虫·搜索引擎·prometheus·easyui·deepseek
0思必得05 小时前
[Web自动化] Selenium中Select元素操作方法
前端·python·selenium·自动化·html
小白学大数据6 小时前
基于 Python 的知网文献批量采集与可视化分析
开发语言·爬虫·python·小程序
飞向天空的鹰6 小时前
反爬虫-开发者调用检测(网页自动关闭)
爬虫
深蓝电商API6 小时前
Scrapy 爬虫监控:结合 Prometheus+Grafana 实践
爬虫·python·scrapy
月明长歌6 小时前
Selenium中隐式等待(Implicit Wait)和显式等待(Explicit Wait)的区别
前端·javascript·selenium
@zulnger7 小时前
刚认识爬虫
爬虫
Rhys..8 小时前
python + selenium 如何定位动态元素
开发语言·python·selenium
翼龙云_cloud8 小时前
阿里云渠道商:弹性伸缩爬虫实战 智能应对流量高峰的 3 步方案
爬虫·阿里云·云计算
0思必得08 小时前
[Web自动化] Selenium浏览器对象属性
前端·python·selenium·自动化·web自动化