python - 使用 Selenium/PhantomJS 进行网络捕获

标签 python python-3.x selenium phantomjs

我想捕获我正在使用 Selenium 和 python 浏览的网站的流量,因为流量将是 https,使用代理不会让我走得太远。

我的想法是使用 selenium 运行 phantomJS 并使用 phantomJS 执行脚本(不是在使用 webdriver.execute_script() 的页面上,而是在 phantomJS 本身上)。我在考虑 netlog.js 脚本(来自这里 https://github.com/ariya/phantomjs/blob/master/examples/netlog.js )。

因为它在命令行中是这样工作的

phantomjs --cookies-file=/tmp/foo netlog.js https://google.com

一定有类似的方法可以用 selenium 做到这一点吗?

提前致谢

更新:

用 browsermob-proxy 解决了。

pip3 install browsermob-proxy

Python3代码

from selenium import webdriver
from browsermobproxy import Server

server = Server(<path to browsermob-proxy>)
server.start()
proxy = server.create_proxy({'captureHeaders': True, 'captureContent': True, 'captureBinaryContent': True})

service_args = ["--proxy=%s" % proxy.proxy, '--ignore-ssl-errors=yes']
driver = webdriver.PhantomJS(service_args=service_args)

proxy.new_har()
driver.get('https://google.com')
print(proxy.har)  # this is the archive
# for example:
all_requests = [entry['request']['url'] for entry in proxy.har['log']['entries']]

最佳答案

我正在为此使用代理

from selenium import webdriver
from browsermobproxy import Server

server = Server(environment.b_mob_proxy_path)
server.start()
proxy = server.create_proxy()
service_args = ["--proxy-server=%s" % proxy.proxy]
driver = webdriver.PhantomJS(service_args=service_args)

proxy.new_har()
driver.get('url_to_open')
print proxy.har  # this is the archive
# for example:
all_requests = [entry['request']['url'] for entry in proxy.har['log']['entries']]

'har'(http 存档格式)有很多关于请求和响应的其他信息,这对我非常有用

在 Linux 上安装:

pip install browsermob-proxy

关于python - 使用 Selenium/PhantomJS 进行网络捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36744627/

相关文章:

python - 使用 Pandas groupby 数据帧中的第一行计算累积差异

Python Pandas DataFrame - 无法在同一轴上绘制条形图和线条

python - 如何强制 PyQt5 用于 QObject 类?

python - Selenium 网络驱动程序 : How to Download a PDF File with Python?

javascript - 使用selenium和Python在iframe内显示图像的src

python - python中的heapq和PriorityQueue有什么区别?

python - 导入错误 : No module named gspread or csv?

python - 获取已知名称的 obj 属性的值

python - 如何检查重复的元音

node.js - 组织3个环境的测试用例