状态码为200的链接重定向

2024-06-16 09:55:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个状态码为200的链接。但当我在浏览器中打开它时,它会重定向。在

在用Python请求获取相同的链接时,它只显示原始链接中的数据。我尝试了Python请求和urllib,但是没有成功。在

  1. 如何捕获最终的URL及其数据?

  2. 状态为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


Tags: theto数据comhttpurlgetis
2条回答

这种重定向是通过JavaScript完成的。因此,您不会使用requests.get(...)直接获取重定向链接。原始URL具有以下页面源:

<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,或者简单地使用一些字符串拆分操作。在

例如:

^{pr2}$

或者,使用正则表达式:

redirected_url = re.findall(r'URL=(http.*)">', r.text)[0]

这类url在script标记中是javascript代码。因此,python不会获取它们。在

要获得链接,只需从它们各自的标记中提取它们。在

相关问题 更多 >