如何使用python在带有自定义标题的浏览器中打开url

2024-03-29 12:52:20 发布

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

我尝试使用webbrowser模块,代码如下,但希望设置自定义标题,例如:

'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1'

以下是我现在掌握的代码:

import webbrowser
webbrowser.open("https://www.bing.com/search?q=TEST123")

我也可以用另一个图书馆。基本上,我希望我的python脚本在我的默认浏览器中打开一个带有自定义标题的url


Tags: 模块代码标题mozillaosmaccpulike
1条回答
网友
1楼 · 发布于 2024-03-29 12:52:20

webbrowser模块的documentation没有提供有关如何访问底层头的信息。看来这是不可能的。如文件所述:

The webbrowser module provides a high-level interface to allow displaying Web-based documents to users.

  1. 在浏览器上使用扩展/插件

您可以使用当前代码并在浏览器上安装扩展,如Firefox或Chrome的simple-modify-headers扩展。(Firefox可以通过this link安装扩展,Chrome可以通过this link安装扩展)

使用这些扩展很容易更改标题值。对于简单的修改标题:

simple-modify-headers settings

还有很多其他扩展/插件,但我不能在这里全部命名。只需搜索“Modify Header extension addon[您的浏览器]”就可以找到一个适合您需要的插件

  1. 使用其他库

您可以使用Selenium Wire。此库可能正是您想要的:

Selenium Wire extends Selenium's Python bindings to give you access to the underlying requests made by the browser. You author your code in the same way as you do with Selenium, but you get extra APIs for inspecting requests and responses and making changes to them on the fly.

示例:

通过pip安装:

pip install selenium-wire

下载并安装浏览器的驱动程序:Chrome DriverGecko Driver

选择与浏览器兼容的版本

获取您的浏览器版本:在Firefox上转到menu > help > about;在Chrome上转到menu > about chrome

安装OpenSSL:

# For apt based Linux systems
sudo apt install openssl

有关安装的更多详细信息,请参阅documentation

from seleniumwire import webdriver  # Import from seleniumwire

# Create a new instance of the Chrome driver (or Firefox)
driver = webdriver.Chrome()

# Create a request interceptor
def interceptor(request):
    del request.headers['User-Agent']  # Delete the header first
    request.headers['User-Agent'] = 'Custom User-Agent'

# Set the interceptor on the driver
driver.request_interceptor = interceptor

# All requests will now use 'some_referer' for the referer
driver.get('https://www.bing.com/search?q=TEST123')

我从this answer派生了上面的代码

如果需要,您可以查看其他浏览器的Selenium's documentation

相关问题 更多 >