【发布时间】:2019-06-04 18:59:05
【问题描述】:
我正在用 Selenium 编写一些测试,并注意到标题中缺少 Referer。我编写了以下最小示例来使用https://httpbin.org/headers 进行测试:
import selenium.webdriver
options = selenium.webdriver.FirefoxOptions()
options.add_argument('--headless')
profile = selenium.webdriver.FirefoxProfile()
profile.set_preference('devtools.jsonview.enabled', False)
driver = selenium.webdriver.Firefox(firefox_options=options, firefox_profile=profile)
wait = selenium.webdriver.support.ui.WebDriverWait(driver, 10)
driver.get('http://www.python.org')
assert 'Python' in driver.title
url = 'https://httpbin.org/headers'
driver.execute_script('window.location.href = "{}";'.format(url))
wait.until(lambda driver: driver.current_url == url)
print(driver.page_source)
driver.close()
哪些打印:
<html><head><link rel="alternate stylesheet" type="text/css" href="resource://content-accessible/plaintext.css" title="Wrap Long Lines"></head><body><pre>{
"headers": {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.5",
"Connection": "close",
"Host": "httpbin.org",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0"
}
}
</pre></body></html>
所以没有Referer。但是,如果我浏览到任何页面并手动执行
window.location.href = "https://httpbin.org/headers"
在 Firefox 控制台中,Referer确实按预期显示。
正如下面的 cmets 所指出的,使用时
driver.get("javascript: window.location.href = '{}'".format(url))
而不是
driver.execute_script("window.location.href = '{}';".format(url))
请求确实包含Referer。此外,当使用 Chrome 而不是 Firefox 时,两种方法都包括Referer。
所以主要问题仍然存在:为什么如上所述使用 Firefox 发送请求时缺少Referer?
【问题讨论】:
-
这里的问题是 Firefox 驱动程序 / Marionette 中的错误。要获取
Referer,请运行driver.get("javascript: window.location.href = 'https://httpbin.org/headers' ")。 -
这是一个错误,因为现有的默认策略不应阻止它,主要是因为它在通过控制台直接更改位置或将驱动程序切换到 Chrome 时存在。
-
不,如果它是由 gecko 驱动程序定义的策略,那么当在控制台中手动更改位置时,您将不会获得
Referer。我的猜测是 JavaScript 沙箱会以某种方式干扰。
标签: python selenium testing http-headers http-referer