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()
相关推荐
SEO_juper4 小时前
hreflang 审计工具:外贸多语言站谷歌SEO的隐性杀手
开发语言·人工智能·爬虫·python·seo
weihubeats5 小时前
10 MB 的 Postman 替代品,启动不到 1 秒
测试工具·postman
深蓝电商API7 小时前
Firecrawl、ScrapeGraphAI:AI爬虫框架横评
人工智能·爬虫·firecrawl·scrapegraphai
小花皮猪9 小时前
从 Prompt 到结构化 JSON:如何利用 Bright Data 快速搭建 YouTube 监测工作流?
人工智能·爬虫·agent·数据采集
云老大-阿里云国际站代理商9 小时前
网站遇到恶意爬虫和CC攻击,阿里云国际站WAF与Bot管理怎么搭配
爬虫·阿里云·云计算
重生之高冷汉堡包11 小时前
Perplexity爬虫怎么做?2026常见方案对比、实操教程与问题排查
大数据·网络·爬虫·安全·ai
傻啦嘿哟11 小时前
设计类网站爬虫:爬取站酷+CNU设计作品,做灵感采集器
爬虫
深蓝电商API1 天前
LLM正在改变爬虫:Crawl4AI源码深度解析
爬虫·crawl4ai
Meta Luo3 天前
UI 自动化测试中的等待、超时和异步加载怎么处理
功能测试·测试工具·ui·回归·自动化
Data_Journal3 天前
如何使用 Selenium 和 Node.js 绕过 CAPTCHA
selenium