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()
相关推荐
西游音月19 小时前
(4)pytest+Selenium自动化测试-元素定位之CSS Selector定位
css·selenium·pytest
x***J34821 小时前
Python多线程爬虫
开发语言·爬虫·python
m***D28621 小时前
Python网络爬虫实战案例
开发语言·爬虫·python
青青子衿_211 天前
TikTok爬取——视频、元数据、一级评论
爬虫·python·selenium
interception1 天前
爬虫js逆向,jsdom补环境,抖音,a_bogus
javascript·爬虫·python
q***2512 天前
Python中的简单爬虫
爬虫·python·信息可视化
程序员小远2 天前
Appium-移动端自动测试框架详解
自动化测试·软件测试·python·测试工具·职场和发展·appium·测试用例
johnny2332 天前
AI加持测试工具汇总:Strix、
人工智能·测试工具
韩师学子--小倪2 天前
tcpdump + Wireshark:抓取nginx转发到服务的流量
测试工具·nginx·tcpdump