首页 > 解决方案 > 使用 Python 跟踪 HTML 或 PHP 重定向?

问题描述

我想用 Python 查看网站的最后一个 URL。我主要使用requestsand urllib2,但欢迎一切。

我正在尝试的网站没有给出Response 302。它使用 HTML 或 PHP 直接重定向。

requests为此使用了模块,但似乎它没有将 HTML PHP 重定向计为“重定向”。

我当前的代码:

def get_real(domain):
    red_domain = requests.get(domain, allow_redirects=True).url
    return red_domain

print(get_real("some_url"))

如果有办法实现这一点,如何实现?提前致谢!


我检查的帖子:


编辑:我正在尝试的 URL:http://001.az。它使用 HTML 进行重定向。

里面的HTML代码:

<HTML> <HEAD><META HTTP-EQUIV=Refresh CONTENT="0; url=http://fm.vc"></HEAD> </HTML>

标签: pythonredirectpython-requests

解决方案


BeautifulSoup 可以帮助检测 HTML 元重定向:

from bs4 import BeautifulSoup

# use request to extract the HTML text
...
soup = BeautifulSoup(html_text.lower(), "html5lib")  # lower because we only want redirections

try:
    content = soup.heap.find('meta', {'http-equiv': 'refresh'}).attrs['content']
    ix = content.index('url=')
    url = content[ix+4:]
    # ok, we have to redirect to url
except AttributeError, KeyError, ValueError:
    url = None

# if url is not None, loop going there...

推荐阅读