python 中爬蟲 content和text的區別


一直在想requests的content和text屬性的區別,從print 結果來看是沒有任何區別

import requests
headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"
}

url = 'https://www.sogou.com/web?query={}'

key = input('請輸入')

params = {'query':key}


response = requests.get(url,params=params,headers=headers)


print(response.text)

 

結論是:text 返回的是unicode 型的數據,一般是在網頁的header中定義的編碼形式。

 

content返回的是bytes,二級制型的數據。

 

 

  # 1. 導入requests模塊
    import requests
    # 2. 發送請求獲取二進制數據(bytes)
    respone =  requests.get("http://imgsrc.baidu.com/image/c0%3Dpixel_huitu%2C0%2C0%2C294%2C40/sign=098c3f828cd6277ffd1f3a7841407a5c/3c6d55fbb2fb4316e3afd1432ba4462309f7d353.jpg")
    # 獲取二進制數據; 注意: 這里不要解碼, 因為圖片,視頻等文件都是二進制的不是文本,不需要解碼
    # data = respone.content
    # 3. 把數據寫入文件
    with open("壁紙.jpg", "wb") as f:
        f.write(respone.content)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM