带有 PhantomJS 的 Selenium 不会被重定向

Selenium with PhantomJS does not get redirected

问题的具体例子,当我在普通浏览器中访问以下地址时:

http://www.aaai.org/ocs/index.php/SOCS/SOCS16/paper/viewFile/13951/13240

我被重定向到 https:

https://www.aaai.org/ocs/index.php/SOCS/SOCS16/paper/viewFile/13951/13240

我在 Python 交互式 shell 中尝试了以下内容:

>>> from selenium import webdriver
>>> driver = webdriver.PhantomJS()
>>> driver.get("http://www.aaai.org/ocs/index.php/SOCS/SOCS16/paper/viewFile/13951/13240")
>>> driver.current_url
u'http://www.aaai.org/ocs/index.php/SOCS/SOCS16/paper/viewFile/13951/13240'

从输出中可以看出,重定向没有发生。我稍等片刻,再次发出 driver.current_url,但输出相同。如何使 Selenium 像在常规浏览器中那样进行重定向?

编辑: 我试图将 Selenium 直接发送到 https 地址,但它不会发送!难道是因为url是一个文件?如果这是正常行为,那么当我只有 http link 时如何找出文件的 url?

问题是您的网页没有使用 30X。相反,它使用了一种不同的方法,即使用 Refresh header。刷新header形式为

Refresh: 5; url=http://www.example.org/fresh-as-a-summer-breeze

其中 5 表示 5 秒后加载 url。您可以看到我如何使用 IPython + Requests

提取它重定向到的 url
In [1]: import requests

In [2]: res = requests.get("http://www.aaai.org/ocs/index.php/SOCS/SOCS16/paper/viewFile/13951/13240")

In [3]: res
Out[3]: <Response [200]>

In [4]: res.text
Out[4]: ''

In [5]: res.headers
Out[5]: {'Date': 'Fri, 29 Sep 2017 10:52:14 GMT', 'Server': 'Apache', 'Refresh': '0; url=https://www.aaai.org/ocs/index.php/SOCS/SOCS16/paper/viewFile/13951/13240', 'Set-Cookie': 'OCSSID=c5eifnobt0942860sraccb2cs0; path=/ocs/', 'Content-Length': '0', 'Keep-Alive': 'timeout=5, max=100', 'Connection': 'Keep-Alive', 'Content-Type': 'text/html; charset=UTF-8'}

In [6]: res.headers['Refresh']
Out[6]: '0; url=https://www.aaai.org/ocs/index.php/SOCS/SOCS16/paper/viewFile/13951/13240'

In [7]: res.headers['Refresh'].split("url=")[-1]
Out[7]: 'https://www.aaai.org/ocs/index.php/SOCS/SOCS16/paper/viewFile/13951/13240'