【问题标题】:Follow HTML or PHP redirects with Python?使用 Python 跟踪 HTML 或 PHP 重定向?
【发布时间】:2020-11-17 20:39:44
【问题描述】:

我想用 Python 查看网站的最后一个 URL。我主要使用requests 和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"))

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


我查看的帖子:


编辑: 我正在尝试的网址:http://001.az。它使用 HTML 来重定向。

里面的HTML代码:

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

【问题讨论】:

  • 可以分享网址吗?
  • 当然,我忘记分享了。现在,我正在编辑问题。
  • 有没有办法做到这一点?是的当然。有简单的方法吗?很不幸的是,不行。您将不得不模仿浏览器会做什么,这意味着解析页面搜索 HEADER bloc 以查找具有属性 HTTP-EQUIV 和值 Refresh 的 META 标记。 BeautifulSoup 可以在这里提供帮助,否则您将不得不使用股票 xml/html 解析器并祈祷 HTML 正确。请在此处说明 BeautifulSoup 是否是一个选项。
  • 谢谢@SergeBallesta!是的,我们可以使用BeautifulSoup 和/或xml/html parser。

标签: python redirect python-requests


【解决方案1】:

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...

【讨论】:

    猜你喜欢
    • 2021-06-13
    • 2017-11-16
    • 2010-09-26
    • 2011-05-26
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 2013-04-15
    • 1970-01-01
    相关资源
    最近更新 更多