使用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()
相关推荐
NeoGressAI外贸数字化3 小时前
外贸独立站robots.txt怎么写:6个AI爬虫放行规则
人工智能·爬虫
OnlineProxy5 小时前
移动应用数据爬取:通过模拟器与流量嗅探对 API 进行逆向工程
爬虫·python·httpx
傻啦嘿哟8 小时前
分布式爬虫架构:Redis+Scrapy打造企业级爬虫系统
分布式·爬虫·架构
梯度下降者20 小时前
零基础入门Python 爬虫
爬虫·python·数据分析·入门指南·webcrawler
2601_967979121 天前
0 到 1 学爬虫:用 Python 爬取网页数据指南一(附实战案例)
爬虫·python·实战案例·html解析·网页数据
姚瑞南1 天前
【PRD】招投标商机雷达爬虫系统
人工智能·经验分享·笔记·爬虫·产品运营·产品经理
嫂子的姐夫2 天前
055-wasm:爬虫练习网spa15(token 纯算还原)
爬虫·wasm
2601_967987372 天前
Python在自动化测试中有哪些应用?
python自动化测试·selenium·appium·pytest·性能测试
深蓝电商API3 天前
用AI生成拟人行为:让鼠标轨迹更“有人味”
人工智能·爬虫
深蓝电商API3 天前
XPath、CSS选择器、正则:什么场景用什么
爬虫·xpath·css选择器