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

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

python3中requests庫重定向獲取URL_python

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

前言:

有時(shí)候 我們抓取一些頁面,發(fā)現(xiàn)一些url 有重定向, 返回 301 ,或者302 這種情況。 那么我們?nèi)绾潍@取真實(shí)的URL呢? 或者跳轉(zhuǎn)后的URL呢?

這里我使用 requests 作為演示

假設(shè)我們要訪問 某東的電子商務(wù)網(wǎng)站,我只記得網(wǎng)站好像是 http://jd.com

import requests

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

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

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

我們?cè)跒g覽器中 chrome network 面板 ,抓包觀察。 注意把 preserve log 這個(gè)選項(xiàng)勾選上。

從 瀏覽器的response header 中 我們可以看到 Location, 從 General 我們可以看到 status code 301 ,發(fā)生了跳轉(zhuǎn)。

方法1:

你現(xiàn)在知道如何獲取跳轉(zhuǎn)后的URL了嗎,直接從response header,獲取 Location 即可。

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

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:

其實(shí)默認(rèn)情況下, requests 會(huì)自動(dòng)跳轉(zhuǎn),如果發(fā)生了重定向,會(huì)自動(dòng)跳到location 指定的URL,我們只需要訪問URL, 獲取response, 然后 response.url 就可以獲取到真實(shí)的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

欄目分類
最近更新