柚子快報邀請碼778899分享:爬蟲基本原理
柚子快報邀請碼778899分享:爬蟲基本原理
一、爬蟲的原理
爬蟲是什么?把互聯(lián)網(wǎng)上的數(shù)據(jù),抓取下來,存到自己的本地。
以百度為例,爬取一個個的網(wǎng)頁,存到自己庫中,當(dāng)我們搜索的時候,去百度的數(shù)據(jù)庫中搜索,顯示在前端,點(diǎn)擊某個頁面,直接跳轉(zhuǎn)到真正的地址。
基本原理: 發(fā)送http請求(requests)---->返回數(shù)據(jù)----->解析數(shù)據(jù)(數(shù)據(jù)清洗,bs4,re…)---->入庫(文件,excel,mysql,redis,mongodb)
注: 爬取數(shù)據(jù)時,如果被禁止了,一定是你模擬的不像。
爬蟲協(xié)議: 每個網(wǎng)站,都有爬蟲協(xié)議,規(guī)定了哪些允許你爬,哪些不允許你爬(君子協(xié)議) robots.txt---->只是一個協(xié)議
反爬:
驗證碼封ip封賬號js逆向:js比較不錯app爬?。杭用躠pp逆向:java,動態(tài)調(diào)試so文件---->匯編
爬蟲所需工具: 請求庫:requests,selenium 解析庫:正則,beautifulsoup,pyquery 存儲庫:文件,MySQL,Mongodb,Redis
爬蟲常用框架: scrapy
二、請求庫requests基本使用
模擬發(fā)送http請求(只要http請求有的東西,都可以使用requests發(fā)送出去)。 python內(nèi)置的urllib2、urllib3,不太好用,用起來比較麻煩。
大神基于urllib3封裝了requests,python界非常出名的第三方庫,只能發(fā)送http請求,不能解析; 又封裝了一個requets-html庫,把request和解析庫封裝到一起了。
安裝:pip3 install requests
1.基本使用
import requests
# res對象中會有,響應(yīng)體,響應(yīng)頭,cookie。。。。
# 請求頭中帶User-Agent,是客戶端類型
# 加入請求頭
res = requests.get('https://dig.chouti.com/',headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'
})
print(res.text) # 響應(yīng)體,轉(zhuǎn)成了字符串
with open('a.html','w',encoding='utf-8') as f:
f.write(res.text)
# 另外一種使用
requests.request('post',cookies={})
2.帶參數(shù)的GET請求
# 方式一:get請求參數(shù),直接拼接在路徑中
response = requests.get('https://www.baidu.com/s?wd=美女',
headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36',
})
with open('baidu.html', 'w', encoding='utf-8') as f:
f.write(response.text)
# 方式二:使用params參數(shù)
response = requests.get('https://www.baidu.com/s',
params={'wd': '帥哥'},
headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36',
})
with open('baidu.html', 'w', encoding='utf-8') as f:
f.write(response.text)
3.帶參數(shù)的GET請求(headers)
import requests
# res對象中會有,響應(yīng)體,響應(yīng)頭,cookie。。。。
# 請求頭中帶User-Agent,是客戶端類型
# referer:上一次請求的地址,做圖片防盜鏈
# cookie:cookie信息
# 加入請求頭
header={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36',
'referer':'https://www.lagou.com/wn/zhaopin'
}
res = requests.get('https://www.lagou.com/gongsi/',headers=header)
print(res.text) # 響應(yīng)體,轉(zhuǎn)成了字符串
referer:比如向這個圖片地址發(fā)請求,會有referer,檢測referer是不是這個網(wǎng)站的,不是則禁止。
4.帶參數(shù)的GET請求(cookies)
# 方式一:帶在請求頭中
header={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36',
'cookie':'deviceId=web.eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqaWQiOiIwZmVlMjk5OS1iMDgzLTRmYzctOTM4MC03YjIzZmVmY2U5YmYiLCJleHBpcmUiOiIxNjIzOTA0ODk5MzM5In0.7cadtBYznS6OgnLwEF8aH0AmtDOoYB1WKDgdU4eYYS0; __snaker__id=VbChmBUEZIVY3FPa; _9755xjdesxxd_=32; YD00000980905869%3AWM_TID=%2FazmF9%2FrClJFEVFBVRN70z7msH6De39Y; Hm_lvt_03b2668f8e8699e91d479d62bc7630f1=1631674964,1634180671,1634183906; gdxidpyhxdE=SmmnuyrMOQB%2B9hzOlIaMPx0O9ZJbqWBllx7aa1OTmRwgGymo94mTYgZ0DrUWw7tfx8qIZmRt01BbIVX2jIc30jqSzPWznXpll6kBokS56266%2FmPg%2BC%5CvNV%2BJhO%5C9ln%2FQdskmo%2FH5A%2BLOADRDACtDp59%5CH51jexwMSIXSA9atTxuJDXOn%3A1634184810108; YD00000980905869%3AWM_NI=WlPwT2GigeoAGFNAH66LZluq3E87sk7E%2Bn6YtGANtE0G%2Bke2f0x6a1rG8kACozd%2FrWBXr3ne%2FBnps6fdDDeTm052UXP1VES3VxQISaL9zd91nvo%2FON%2FVuXS9INJSQYS%2FOG8%3D; YD00000980905869%3AWM_NIKE=9ca17ae2e6ffcda170e2e6ee97c96aadeda38de27286ef8bb3d45a828f8babae8095aea8d0b47e9191e186c42af0fea7c3b92a95b4a098d73a85b7a986ee4b859a82a2cb3ef694968df87bf19bf8d8f261f59be58fb553b8998faff74ff499e58ce83aa6f0b8d7e43bb299f88cc449ada6acd0f15d8288bed4ed6fed9ea291f23ea6bc8ca5e860aff0fbd3d85494ef9aa6d23996a89faad26b90e7b685bc3baeaaa1d0ce46ed8abbb9d2338b9286b4d45391f181a8bb37e2a3; token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqaWQiOiJjZHVfNTMyMDcwNzg0NjAiLCJleHBpcmUiOiIxNjM2Nzc1OTIyMTI2In0.o5-Y9-USxFog5sdo1WR1WORUzPkUD4fozEVA_f0WSHU; Hm_lpvt_03b2668f8e8699e91d479d62bc7630f1=1634183939'
}
# post請求,攜帶在請求體中的數(shù)據(jù)
res=requests.post('https://dig.chouti.com/link/vote',data={'linkId': '32667354'},headers=header)
#https://dig.chouti.com/link/cancel/vote
print(res.text)
# 方式二:直接以參數(shù)形式傳入,cookie會經(jīng)常用,而且一般是字典形式,提供了一個cookie參數(shù)
header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36',
}
# cookies需要是:Dict or CookieJar object
res = requests.post('https://dig.chouti.com/link/vote', data={'linkId': '32667354'}, headers=header,cookies={})
print(res.text)
5.POST請求
# 發(fā)送post請求,模擬瀏覽器的登錄行為
header = {
'Referer': 'http://www.aa7a.cn/user.php?&ref=http%3A%2F%2Fwww.aa7a.cn%2F',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'
}
res = requests.post('http://www.aa7a.cn/user.php', headers=header, data={
'username': 'xxx@qq.com',
'password': 'xxx',
'captcha': 'fmd8',
'remember': 1,
'ref': 'http://www.aa7a.cn/',
'act': 'act_login',
})
# 獲取到cookie,登陸過后的cookie
cookie = res.cookies
print(cookie) # CookieJar
res1 = requests.get('http://www.aa7a.cn/', headers=header, cookies=cookie)
# res1=requests.get('http://www.aa7a.cn/',headers=header)
print('xxx@qq.com' in res1.text)
6.響應(yīng)Response
import requests
respone=requests.get('http://www.360buy.com')
# respone屬性
print(respone.text) # body的內(nèi)容轉(zhuǎn)成str類型
print(respone.content) # body的二進(jìn)制內(nèi)容 (圖片,視頻)
print(respone.status_code) # 響應(yīng)狀態(tài)碼
print(respone.headers) # 響應(yīng)頭
print(respone.cookies) # 把響應(yīng)的cookie轉(zhuǎn)成了cookiejar的對象
print(respone.cookies.get_dict()) # 把cookiejar的對象轉(zhuǎn)成字典
print(respone.cookies.items()) # key和value
print(respone.url) # 請求的地址
print(respone.history) # 請求歷史,重定向,才有數(shù)據(jù),列表
print(respone.encoding) # 響應(yīng)的編碼格式
response.iter_content() #循環(huán)它,如果是視頻,一點(diǎn)一點(diǎn)保存
解析json(http請求返回的數(shù)據(jù)是json格式): res.text是json字符串,取值不好取,需要json.loads(res.text)轉(zhuǎn)成字典,再取值 直接res.json()轉(zhuǎn)成json后的字典形式
import requests
res = requests.post('http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword', data={
'cname': '',
'pid': '',
'keyword': '上海',
'pageIndex': 1,
'pageSize': 10,
})
# print(res.text)
print(type(res.json()))
7.編碼問題 url編碼問題 把中文用url編碼,把url編碼解成中文
# https://www.baidu.com/s?wd=%E7%BE%8E%E5%A5%B3
from urllib import parse
# 把中文用url編碼,
res=parse.quote('美女')
print(res)
# 把url編碼解成中文
res=parse.unquote('%E7%BE%8E%E5%A5%B3')
print(res)
網(wǎng)站編碼,不是utf-8,使用res.text默認(rèn)用utf-8轉(zhuǎn),可能出亂碼
import requests
res=requests.get('')
# res.encoding='GBK'
res.encoding=res.apparent_encoding
print(res.text)
8.獲取二進(jìn)制數(shù)據(jù) 視頻、圖片需要保存二進(jìn)制
import requests
res=requests.get('https://img.lianzhixiu.com/uploads/allimg/202001/9999/a7b0199df8.jpg')
with open('致命誘惑2.png','wb') as f:
# f.write(res.content)
for line in res.iter_content(1024):
f.write(line)
9.request.session的使用
import requests
session = requests.session() # 可以幫咱們保持cookie,以后不用手動攜帶
header = {
'Referer': 'http://www.aa7a.cn/user.php?&ref=http%3A%2F%2Fwww.aa7a.cn%2F',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'
}
res = session.post('http://www.aa7a.cn/user.php', headers=header, data={
'username': 'xxx@qq.com',
'password': 'xxx',
'captcha': 'fmd8',
'remember': 1,
'ref': 'http://www.aa7a.cn/',
'act': 'act_login',
})
# 獲取到cookie,登陸過后的cookie
# cookie=res.cookies
# print(cookie) # CookieJar
res1 = session.get('http://www.aa7a.cn/', headers=header)
print('xxx@qq.com' in res1.text)
補(bǔ)充: 什么是正向代理,什么是反向代理?
正向代理,隱藏客戶端 翻墻軟件 反向代理,隱藏服務(wù)器 nginx 是一個反向代理服務(wù)器
正向代理---->買票的黃牛 反向代理---->租房的代理
總結(jié): 1 爬蟲介紹
模擬發(fā)送http請求---->獲取到數(shù)據(jù)(html,json,圖片,視頻)---->數(shù)據(jù)清洗---->入庫
2 請求庫:requests模塊
跟其他服務(wù)交互,使用requests模塊postman:完全自己寫,使用requests寫
3 發(fā)送get請求
4 發(fā)送get請求,地址中帶參數(shù)
直接拼在路徑中params參數(shù)傳入,字典url編碼和解碼:中文編成url的編碼形式
5 發(fā)送get請求,攜帶請求頭
headers參數(shù)user-agent:客戶端類型referer:上一個地址
6 發(fā)送請求,攜帶cookie 請求頭 以參數(shù)形式攜帶
7 發(fā)送post請求
地址中帶數(shù)據(jù):params參數(shù)傳入請求頭中帶:headers請求體中:data={},json={}
8 Respons對象屬性,參數(shù)
text:響應(yīng)的body體,轉(zhuǎn)成了字符串content:響應(yīng)體的二進(jìn)制(圖片,視頻)iter_content:圖片,視頻,循環(huán)保存編碼cookies:一旦登錄成功,這個cookies就是認(rèn)證后的cookiesjson() :把返回的json格式字符串直接轉(zhuǎn)成字典形式
9 編碼問題
10 request.session的使用
柚子快報邀請碼778899分享:爬蟲基本原理
精彩文章
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點(diǎn)和立場。
轉(zhuǎn)載請注明,如有侵權(quán),聯(lián)系刪除。