如何在 Selenium 中获取请求标头

use*_*085 7 python selenium fiddler

https://www.sahibinden.com/en
Run Code Online (Sandbox Code Playgroud)

如果您打开它的隐身窗口并在 Fiddler 中检查标题,那么这些是您获得的两个主要标题: 在此处输入图片说明

当我单击最后一个并检查请求标头时,这就是我得到的 在此处输入图片说明

我想在 Python 中获取这些标头。有什么办法可以使用 Selenium 获得这些吗?我在这里有点不知所措。

小智 13

您可以使用硒线。它是为此目的而开发的 Selenium 扩展。

https://pypi.org/project/selenium-wire/

pip 安装后的示例:

##  Import webdriver from Selenium Wire instead of Selenium
from seleniumwire import webdriver

##  Get the URL
driver = webdriver.Chrome("my/path/to/driver", options=options)
driver.get("https://my.test.url.com")

##  Print request headers
for request in driver.requests:
  print(request.url) # <--------------- Request url
  print(request.headers) # <----------- Request headers
  print(request.response.headers) # <-- Response headers
Run Code Online (Sandbox Code Playgroud)


小智 12

你可以像这样运行 JS 命令;

var req = new XMLHttpRequest()
req.open('GET', document.location, false)
req.send(null)
return req.getAllResponseHeaders()
Run Code Online (Sandbox Code Playgroud)

关于Python;

driver.get("https://t.me/codeksiyon")
headers = driver.execute_script("var req = new XMLHttpRequest();req.open('GET', document.location, false);req.send(null);return req.getAllResponseHeaders()")

# type(headers) == str

headers = headers.splitlines()
Run Code Online (Sandbox Code Playgroud)

  • 这些是响应标头。OP想要REQUEST标头 (6认同)

Deb*_*anB 7

最重要的是,,您无法使用Selenium检索请求标头。


细节

Selenium 用户长期以来一直要求添加 WebDriver方法来从 HTTP 响应中读取 HTTP 状态代码和标头。我们在WebDriver 缺少 HTTP 响应头和状态代码方法的讨论中详细讨论了通过 Selenium 实现此功能。

然而,Jason Leyba(Selenium 贡献者)在他的评论中直接提到:

我们不会将此功能添加到 WebDriver API 中,因为它超出了我们当前的范围(模拟用户操作)。

Ashley Leyba 进一步补充道,试图使 WebDriver 成为理想的 Web 测试工具,driver.get(url)在浏览器加载页面并返回最终加载页面的响应之前,整体质量将受到阻碍。因此,在登录重定向的情况下,状态代码和标头将始终以 200 而不是您要查找的 302 结束。

最后,Simon M Stewart(WebDriver 创建者)在评论中得出结论:

这个功能不会发生。推荐的方法是扩展HtmlUnitDriver以访问您需要的信息,或者使用公开此信息的外部代理,例如BrowserMob 代理


小智 -2

使用 Selenium 无法获取标头。更多信息

但是,您可以使用其他库(例如requests, )BeautifulSoup来获取标头。


归档时间:

查看次数:

14236 次

最近记录:

4 年,8 月 前