硒/幻影网络捕捉

2024-03-28 11:29:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我想通过python使用Selenium来捕获我正在浏览的站点的流量,因为使用代理的流量将是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

一定有类似的方法来处理硒?

提前谢谢

更新:

用browsermob代理解决了这个问题。

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']]

Tags: httpscomtrue代理serverservicejsargs
2条回答

我在用一个代理

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

我使用一个没有代理服务器的解决方案。为了添加executePhantomJS函数,我根据下面的链接修改了selenium源代码。

https://github.com/SeleniumHQ/selenium/pull/2331/files

然后在获取phantomJS驱动程序后执行以下脚本:

from selenium.webdriver import PhantomJS

driver = PhantomJS()

script = """
    var page = this;
    page.onResourceRequested = function (req) {
        console.log('requested: ' + JSON.stringify(req, undefined, 4));
    };
    page.onResourceReceived = function (res) {
        console.log('received: ' + JSON.stringify(res, undefined, 4));
    };
"""

driver.execute_phantomjs(script)
driver.get("http://ariya.github.com/js/random/")
driver.quit()

然后所有请求都记录在控制台中(通常是ghostdriver.log文件)

相关问题 更多 >