我的代码如下:
url_orig ='http://www.has-sante.fr/portail/jcms/c_676945/fr/prialt-ct-5245'
u = urllib.request.urlopen(url_orig)
print (u.geturl())
基本上当 URL 被重定向两次时。输出应该是:
http://www.has-sante.fr/portail/upload/docs/application/pdf/2008-07/ct-5245_prialt_.pdf
但我得到的输出是第一个重定向:
http://www.has-sante.fr/portail/plugins/ModuleXitiKLEE/types/FileDocument/doXiti.jsp?id=c_676945
如何获得所需的最终 URL?任何帮助将不胜感激!
最佳答案
这对于您想要的可能有点矫枉过正,但它是使用正则表达式的替代方法。此答案使用 Selenium 网络自动化器 Python APIs跟随重定向。它还将在浏览器窗口中打开 pdf 文件。下面的代码要求您使用 Firefox,但您也可以通过将名称替换为您想要使用的名称来使用其他浏览器,即 webdriver.Chrome()、webdriver.Ie()。
安装 Selenium :pip install selenium
代码:
from selenium import webdriver
driver = webdriver.Firefox()
link = 'http://www.has-sante.fr/portail/jcms/c_676945/fr/prialt-ct-5245'
driver.get(link)
print(driver.current_url)
也可以在后台运行浏览器,这样就不会弹出窗口。此解决方案的额外好处是,如果它们改变了重定向的工作方式,您将无需更新代码中的正则表达式。
关于python - 获取最终重定向的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24339236/