【问题标题】:Link with status code 200 redirects带有状态码 200 重定向的链接
【发布时间】:2018-09-05 21:09:59
【问题描述】:
我有一个状态码为 200 的链接。但是当我在浏览器中打开它时,它会重定向。
在使用 Python 请求获取相同的链接时,它只显示来自原始链接的数据。我尝试了 Python Requests 和 urllib,但都没有成功。
如何获取最终 URL 及其数据?
状态为 200 的链接如何重定向?
>>> url ='http://www.afaqs.com/news/story/52344_The-target-is-to-get-advertisers-to-switch-from-print-to-TV-Ravish-Kumar-Viacom18'
>>> r = requests.get(url)
>>> r.url
'http://www.afaqs.com/news/story/52344_The-target-is-to-get-advertisers-to-switch-from-print-to-TV-Ravish-Kumar-Viacom18'
>>> r.history
[]
>>> r.status_code
200
This is the link
Redirected link
【问题讨论】:
标签:
python
python-3.x
redirect
python-requests
【解决方案1】:
这种重定向是由 JavaScript 完成的。因此,您不会使用requests.get(...) 直接获得重定向链接。原网址有以下页面来源:
<html>
<head>
<meta http-equiv="refresh" content="0;URL=http://www.afaqs.com/interviews/index.html?id=572_The-target-is-to-get-advertisers-to-switch-from-print-to-TV-Ravish-Kumar-Viacom18">
<script type="text/javascript" src="http://gc.kis.v2.scr.kaspersky-labs.com/D5838D60-3633-1046-AA3A-D5DDF145A207/main.js" charset="UTF-8"></script>
</head>
<body bgcolor="#FFFFFF"></body>
</html>
在这里,您可以看到重定向的 URL。你的工作就是把它刮掉。您可以使用 RegEx 或简单的一些字符串拆分操作来完成。
例如:
r = requests.get('http://www.afaqs.com/news/story/52344_The-target-is-to-get-advertisers-to-switch-from-print-to-TV-Ravish-Kumar-Viacom18')
redirected_url = r.text.split('URL=')[1].split('">')[0]
print(redirected_url)
# http://www.afaqs.com/interviews/index.html?id=572_The-target-is-to-get-advertisers-to-switch-from-print-to-TV-Ravish-Kumar-Viacom18
r = requests.get(redirected_url)
# Start scraping from this link...
或者,使用正则表达式:
redirected_url = re.findall(r'URL=(http.*)">', r.text)[0]
【解决方案2】:
这些类型的 url 存在于 script 标签中,因为它们是 javascript 代码。因此它们也不会被 python 获取。
要获取链接,只需从它们各自的标签中提取它们。