python爬虫源码:selenium+browsermobproxy实现浏览器请求抓取

前言

如上篇博客所述:为了抓取所有,通过浏览器F12可以看到的资源(静态资源和接口调用),我使用了selenium+browsermobproxy的方案来处理。

这是两个模块的安装方案,没有看过的朋友可以去了解一下:

python爬虫:selenium+browsermobproxy实现浏览器请求抓取(模块安装详解)-CSDN博客

下面是我编写的一些python代码,可以帮助你尽快入门:

代码

python 复制代码
# encoding=utf-8

from browsermobproxy import Server
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
import time
import json

# 启动BrowserMob Proxy
server = Server(r"E:\其他源码\browsermob-proxy-2.1.4-bin\browsermob-proxy-2.1.4\bin\browsermob-proxy.bat")  # 替换为BrowserMob Proxy的路径
server.start()

# 使用网络代理,如果你需要的话
# proxy = server.create_proxy({"httpProxy":"127.0.0.1:7890"})
proxy = server.create_proxy()

# 设置Chrome WebDriver
chrome_service = Service(r"E:\其他源码\chromedriver-win64\chromedriver.exe")  # 替换为WebDriver的路径

chrome_options = Options()
chrome_options.add_argument("--proxy-server={0}".format(proxy.proxy))

# 解决 您的连接不是私密连接问题
chrome_options.add_argument('--ignore-certificate-errors')
chrome_options.add_argument('--ignore-urlfetcher-cert-requests')

driver = webdriver.Chrome(service=chrome_service, options=chrome_options)


# 设置代理捕获HAR数据
proxy.new_har("comic_order", options={'captureHeaders': True, 'captureContent': True})
# 访问链接A(需要触发POST请求的页面)
driver.get(f"https://xxxxxxxxxxxxxx")  # 替换为实际的初始页面URL

# 可能需要等待页面加载
time.sleep(15)  # 可以根据需要调整等待时间

# 处理可能的弹出窗口操作,手动或自动化操作,取决于您的具体网站逻辑
# 例如,假设点击某个按钮会弹出窗口
# driver.find_element(By.ID, "your_button_id").click()  # 根据具体情况选择元素并点击

# 你可能只需要每次抓取众多响应中的某个接口数据
target_url = 'http://xxxxxxxxxxx'

# 获取并分析HAR数据
har_data = proxy.har
for entry in har_data['log']['entries']:
    req = entry['request']
    url = req['url']
    if url == target_url and entry['response']:
        try:
            # 获取接口数据
            result = json.loads(entry['response']['content']['text'])  # 解析为JSON格式
            print("解析后的JSON内容:", result)

            # 加入 接下来需要对数据进行处理的操作
            print('do something?')

        except json.JSONDecodeError as e:
            print("解析JSON失败:", e)
        except Exception as e:
            print(e)

        break

# 关闭浏览器和代理服务器
driver.quit()
server.stop()
相关推荐
Caco_D1 天前
一行代码抓遍全网 20 个热榜!Aneiang.Pa 4.0 发布 — 极简 .NET 爬虫库
爬虫·.net
太岁又沐风6 天前
复现并修掉ART hook框架 Pine 调用原方法时的偶发 SIGSEGV
爬虫
隔窗听雨眠7 天前
大模型加爬虫上篇:技术融合与架构革新
爬虫·架构
程序员小远7 天前
自动化测试基础知识总结
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
Super Scraper7 天前
如何批量抓取 TikTok 数据而不被封锁?完整指南
爬虫·ai·自动化·抖音·tiktok·ai agent
深蓝电商API7 天前
自动化录屏 + 截图:打造爬虫调试的上帝视角
爬虫
tang777897 天前
市场调研自动化采集架构:基于住宅IP轮换的APP数据抓取与反风控方案
爬虫·动态代理ip·爬虫代理ip·爬虫动态ip·住宅代理ip·动态住宅ip
数据知道7 天前
指纹浏览器环境的导入、导出、快照与云端同步机制
爬虫·数据采集·指纹浏览器
星川皆无恙7 天前
大数据k-means聚类算法:基于k-means聚类算法+NLP微博舆情数据爬虫可视化分析推荐系统(新版)
大数据·人工智能·爬虫·算法·机器学习·自然语言处理·kmeans