日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python3中requests庫重定向獲取URL_python

作者:阿常囈語 ? 更新時間: 2022-11-16 編程語言

前言:

有時候 我們抓取一些頁面,發現一些url 有重定向, 返回 301 ,或者302 這種情況。 那么我們如何獲取真實的URL呢? 或者跳轉后的URL呢?

這里我使用 requests 作為演示

假設我們要訪問 某東的電子商務網站,我只記得網站好像是 http://jd.com

import requests

def request_jd():
    url = 'http://jd.com/'
    #allow_redirects= False 這里設置不允許跳轉
    response = requests.get(url=url, allow_redirects=False)

    print(response.headers)
    print(response.status_code)
    

看結果 返回response header 中有一個屬性 Location ,代表重定向了 'Location': 'https://www.jd.com'

我們在瀏覽器中 chrome network 面板 ,抓包觀察。 注意把 preserve log 這個選項勾選上。

從 瀏覽器的response header 中 我們可以看到 Location, 從 General 我們可以看到 status code 301 ,發生了跳轉。

方法1:

你現在知道如何獲取跳轉后的URL了嗎,直接從response header,獲取 Location 即可。

在request.header 中 返回header 的key是不區分大小寫的, 所以全小寫也是可以正確取值的。

import requests

def request_jd():
    url = 'http://jd.com/'
    response = requests.get(url=url, allow_redirects=False)
    #return response.headers.get('location')
    return response.headers.get('Location')

方法2:

其實默認情況下, requests 會自動跳轉,如果發生了重定向,會自動跳到location 指定的URL,我們只需要訪問URL, 獲取response, 然后 response.url 就可以獲取到真實的URL啦。

import requests

def request_jd():
    url = 'http://jd.com/'
    response = requests.get(url=url)
	
    return response.url

原文鏈接:https://blog.csdn.net/u010339879/article/details/119517222

欄目分類
最近更新