python - 使用 Python 跟踪 HTML 或 PHP 重定向?
问题描述
我想用 Python 查看网站的最后一个 URL。我主要使用requests
and 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>
解决方案
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...
推荐阅读
- linux - ALSA ASoC 简单声卡驱动程序中的 DAPM 路由是什么意思?
- datetime - Neo4j 建模时间线的最佳方法
- css - Bootstrap 折叠菜单/下拉菜单颜色问题
- python - 如何找到多个文档中存在的所有最长公共子字符串?
- string - 我可以将 Twig 变量标记为与捕获的文本块一样安全吗?
- c# - 具有相同数据源的 DataGridView 和 ListBox 选择相同的元素
- bitbucket-pipelines - 为多个项目创建单个 bitbucket-pipelines.yml 文件
- ios - 动画 UIStackView 子视图会导致布局问题
- python - 计算 Pandas 中两个值内的位置的计数
- matlab - 使用 MATLAB 的 GPU 功能计算 sum(a.*exp(b.*c),1) 的有效方法