簡體   English   中英

鏈接狀態代碼200重定向

[英]Link with status code 200 redirects

我有一個狀態代碼為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

這是鏈接

重定向鏈接

這種重定向是由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或簡單的字符串拆分操作來完成。

例如:

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]

這些url存在於腳本標記中,因為它們是javascript代碼。 因此它們也不是由python提取的。

要獲取鏈接,只需從各自的標簽中提取它們即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM