【问题标题】:Network capturing with Selenium/PhantomJS使用 Selenium/PhantomJS 进行网络捕获
【发布时间】:2016-08-13 04:20:06
【问题描述】:

我想使用 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

硒必须有类似的方法吗?

提前致谢

更新:

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

【问题讨论】:

  • 除了用pip安装python库外,还需要从https://github.com/lightbody/browsermob-proxy/releases下载最新版本的bmp并安装java运行环境apt-get install default-jre.&lt;path to browsermob-proxy&gt;然后设置为您将 bmp 下载到的路径。

标签: python python-3.x selenium phantomjs


【解决方案1】:

我正在为此使用代理

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

【讨论】:

  • 谢谢,也成功了。虽然对于 Python3,您需要更改一些代码和 phantomJS 参数。在我的帖子中更新了它。
  • 改用driver = webdriver.Chrome(service_args=service_args),效果很好
【解决方案2】:

如果这里有人正在寻找纯 Selenium/Python 解决方案,以下 sn-p 可能会有所帮助。它使用 Chrome 记录所有请求,并作为示例打印所有 json 请求及其相应的响应。

from time import sleep

from selenium import webdriver
from selenium.webdriver import DesiredCapabilities

# make chrome log requests
capabilities = DesiredCapabilities.CHROME

capabilities["loggingPrefs"] = {"performance": "ALL"}  # chromedriver < ~75
# capabilities["goog:loggingPrefs"] = {"performance": "ALL"}  # chromedriver 75+

driver = webdriver.Chrome(
    desired_capabilities=capabilities, executable_path="./chromedriver"
)

# fetch a site that does xhr requests
driver.get("https://sitewithajaxorsomething.com")
sleep(5)  # wait for the requests to take place

# extract requests from logs
logs_raw = driver.get_log("performance")
logs = [json.loads(lr["message"])["message"] for lr in logs_raw]

def log_filter(log_):
    return (
        # is an actual response
        log_["method"] == "Network.responseReceived"
        # and json
        and "json" in log_["params"]["response"]["mimeType"]
    )

for log in filter(log_filter, logs):
    request_id = log["params"]["requestId"]
    resp_url = log["params"]["response"]["url"]
    print(f"Caught {resp_url}")
    print(driver.execute_cdp_cmd("Network.getResponseBody", {"requestId": request_id}))

要点:https://gist.github.com/lorey/079c5e178c9c9d3c30ad87df7f70491d

【讨论】:

    【解决方案3】:

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

    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文件)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-04
      • 2021-02-28
      • 2020-09-04
      • 2013-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多