提前宣告:該專欄涉及的所有案例均為學習使用,如有侵權,請聯系本人刪帖!
文章目錄
- 一、請求頭中的cookie
- 二、準備作業
- 三、分析
- 四、代碼撰寫
一、請求頭中的cookie
對于一些網站,我們在抓取時候需要補充請求頭requests headers
Host: www.renren.com
Proxy-Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3877.400 QQBrowser/10.8.4506.400
Accept: text/html
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9
Cookie: ***
但是對于一些網站,我們如果不登錄,那么我們就無法進入網站內部,因此就需要登錄,那么登錄后,我們就可以獲取到cookie值,而有了cookie值,我們就可以進入網站,抓取想要的資訊,
二、準備作業
- 環境:python3.6
- 開發工具:pycharm
- 模塊:requests
三、分析
網站:https://codechina.csdn.net/explore/welcome
進入網址,需要登錄

因此我們需要手動登錄后,然后看到已經有了cookie


因此我們直接在請求的時候攜帶自己的cookie,如果我們登陸后,可以看到自己的用戶名

四、代碼撰寫
# -*- coding: utf-8 -*-
import requests
url = 'https://codechina.csdn.net/explore/welcome'
headers = {
'Cookie': '...',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36'
}
# 請求,verify=False 跳過ssl驗證
response = requests.get(url, headers=headers, verify=False)
response.encoding = 'utf-8'
if '不愿透露姓名の網友' in response.text:
print('cookie有效')
else:
print('cookie無效')

成功!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/310551.html
標籤:其他
上一篇:商城系統的可行性與需求
