餐飲品牌形象設(shè)計(jì)案例seo工程師
文章目錄
- 一、基于 Cookie 的模擬登錄
- 二、基于 JWT 模擬登入
- 三、賬號(hào)池
- 四、基于 Cookie 模擬登錄爬取實(shí)戰(zhàn)
- 五、基于JWT 的模擬登錄爬取實(shí)戰(zhàn)
- 六、構(gòu)建賬號(hào)池
很多情況下,網(wǎng)站的一些數(shù)據(jù)需要登錄才能查看,如果需要爬取這部分的數(shù)據(jù),就需要實(shí)現(xiàn)模擬登入的一些機(jī)制;模擬登錄現(xiàn)在主要分為兩種方式,一種是基于 Session 和 Cookie 的模擬登入,一種是基于 JWT(Json Web Token)的模擬登錄。
對(duì)于第一種模式,打開(kāi)網(wǎng)頁(yè)后模擬登錄,服務(wù)器會(huì)返回帶有 Set-Cookie 字段的響應(yīng)頭,客戶(hù)端會(huì)生成對(duì)應(yīng)的 Cookie,其中保存著與 SessionID 相關(guān)的信息,之后發(fā)送給服務(wù)器的請(qǐng)求都會(huì)攜帶這個(gè)生成的 Cookie。服務(wù)器接收到請(qǐng)求后,會(huì)根據(jù) Cookie 中保存的 SessionID 找到對(duì)應(yīng)的 Session,同時(shí)效驗(yàn) Cookie 里的相關(guān)信息,如果當(dāng)前 Session 是有效的并且效驗(yàn)成功,服務(wù)器就判斷當(dāng)前用戶(hù)已經(jīng)登錄,返回請(qǐng)求的頁(yè)面信息,所以這種模式的核心是獲取客戶(hù)端登錄后生成的 Cookie;
對(duì)于第二種模式,是因?yàn)楝F(xiàn)在有很多的網(wǎng)站采取的開(kāi)發(fā)模式是前后端分離模式,所以使用 JWT 進(jìn)行登錄效驗(yàn)越來(lái)越普遍,在請(qǐng)求數(shù)據(jù)時(shí),服務(wù)器會(huì)效驗(yàn)請(qǐng)求中攜帶的 JWT 是否有效,如果有效,就返回正常的數(shù)據(jù),所以這種模式其實(shí)就是獲取 JWT;
一、基于 Cookie 的模擬登錄
如果要使用爬蟲(chóng)實(shí)現(xiàn)基于 Session 和 Cookie 的模擬登錄,最為主要的是要維護(hù)好 Cookie 的信息,因?yàn)榕老x(chóng)相當(dāng)于客戶(hù)端的瀏覽器;
- 如果在瀏覽器中登錄了自己的賬號(hào),可以直接把網(wǎng)頁(yè)中的 Cookie 復(fù)制給爬蟲(chóng),就相當(dāng)于手動(dòng)在瀏覽器中登錄;
- 如果讓爬蟲(chóng)完全自動(dòng)化操作,可以直接使用爬蟲(chóng)模擬登錄過(guò)程,這個(gè)過(guò)程基本上就是一個(gè) POST 請(qǐng)求,用爬蟲(chóng)把用戶(hù)名,密碼等信息提交給服務(wù)器,服務(wù)器會(huì)返回一個(gè) Set-Cookie 字段,我們只需要將該字段保存下來(lái),然后提交給爬蟲(chóng)請(qǐng)求就好;
- 如果 POST 請(qǐng)求難以構(gòu)造,我們可以使用自動(dòng)化工具來(lái)模擬登錄,例如使用 Selenium,Playwright 來(lái)發(fā)送請(qǐng)求,然后獲取 Cookie 進(jìn)行發(fā)送請(qǐng)求;
二、基于 JWT 模擬登入
JWT 的字符串就是用戶(hù)訪(fǎng)問(wèn)的憑證,所以模擬登錄只需要做到以下幾步:
- 模擬登錄操作,例如拿著用戶(hù)名和密碼信息請(qǐng)求登錄接口,獲取服務(wù)器返回的結(jié)果,這個(gè)結(jié)果中通常包含 JWT 信息,將其保存下來(lái)即可;
- 之后發(fā)送給服務(wù)器的請(qǐng)求均攜帶 JWT,在 JWT 不過(guò)期的情況下,通常能正常訪(fǎng)問(wèn)和執(zhí)行操作,攜帶方式多種多樣,因網(wǎng)站而異;
- 如果 JWT 過(guò)期了,可能需要再次做第一步,重新獲取 JWT;
三、賬號(hào)池
如果爬蟲(chóng)要求爬取的數(shù)據(jù)量比較大,或者爬取速度比較快,網(wǎng)站又有單賬號(hào)并發(fā)限制或者訪(fǎng)問(wèn)狀態(tài)檢測(cè)等反爬蟲(chóng)手段,我們的賬號(hào)可能就無(wú)法訪(fǎng)問(wèn)網(wǎng)站或者面臨封號(hào)的風(fēng)險(xiǎn);
這時(shí)我們建立一個(gè)賬號(hào)池進(jìn)行分流,用多個(gè)賬號(hào)隨機(jī)訪(fǎng)問(wèn)網(wǎng)站或爬取數(shù)據(jù),這樣能大幅提高爬蟲(chóng)的并發(fā)量,降低被封號(hào)的風(fēng)險(xiǎn),例如準(zhǔn)備 100 個(gè)賬號(hào),將這 100 個(gè)賬號(hào)都模擬登錄,并保存對(duì)應(yīng)的 Cookie 和 JWT,每次都隨機(jī)抽取一個(gè)來(lái)訪(fǎng)問(wèn),賬號(hào)多,所以每個(gè)賬號(hào)被選取的概率就小,也就避免了單賬號(hào)并發(fā)量過(guò)大的問(wèn)題,從而降低封號(hào)風(fēng)險(xiǎn);
四、基于 Cookie 模擬登錄爬取實(shí)戰(zhàn)
目標(biāo)網(wǎng)址:Scrape | Movie

賬號(hào):admin
密碼:admin
這里由于登入請(qǐng)求構(gòu)造并沒(méi)有涉及到加密過(guò)程,因此我們可以直接構(gòu)造 requests 請(qǐng)求來(lái)執(zhí)行請(qǐng)求;仔細(xì)分析后可以發(fā)現(xiàn)登入請(qǐng)求返回的狀態(tài)碼是 302,同時(shí)登入完畢后頁(yè)面自動(dòng)發(fā)生了跳轉(zhuǎn),因此在使用 requests 夠著 post 請(qǐng)求的時(shí)候,需要將 allow_redirects 參數(shù)設(shè)置為 False;
import requests
import parselheaders = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7','Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6','Cache-Control': 'max-age=0','Connection': 'keep-alive','Content-Type': 'application/x-www-form-urlencoded','Origin': 'https://login2.scrape.center','Referer': 'https://login2.scrape.center/login','Sec-Fetch-Dest': 'document','Sec-Fetch-Mode': 'navigate','Sec-Fetch-Site': 'same-origin','Sec-Fetch-User': '?1','Upgrade-Insecure-Requests': '1','User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0','sec-ch-ua': '"Not/A)Brand";v="8", "Chromium";v="126", "Microsoft Edge";v="126"','sec-ch-ua-mobile': '?0','sec-ch-ua-platform': '"Windows"',
}data = {'username': 'admin','password': 'admin',
}response = requests.post('https://login2.scrape.center/login', headers=headers, data=data, allow_redirects=False)# 得到 cookies
cookies = response.cookies.get_dict()# 將獲取到的 cookie 放入 requests 的 get 請(qǐng)求中
response = requests.get('https://login2.scrape.center/', cookies=cookies, headers=headers)# 解析網(wǎng)頁(yè)數(shù)據(jù)
selector = parsel.Selector(response.text)
names = selector.xpath('//*[@id="index"]/div[1]/div[1]/div/div/div/div[2]/a/h2/text()').getall()# 打印名字
print(names)# ['霸王別姬 - Farewell My Concubine',
# '這個(gè)殺手不太冷 - Léon',
# '肖申克的救贖 - The Shawshank Redemption',
# '泰坦尼克號(hào) - Titanic',
# '羅馬假日 - Roman Holiday',
# '唐伯虎點(diǎn)秋香 - Flirting Scholar',
# '亂世佳人 - Gone with the Wind',
# '喜劇之王 - The King of Comedy',
# '楚門(mén)的世界 - The Truman Show',
# '獅子王 - The Lion King']
在這里我們首先獲得了 cookies,然后又手動(dòng)要將 cookies 放入到后續(xù)的請(qǐng)求之中,這里我們可以構(gòu)建 Session 請(qǐng)求來(lái)自動(dòng)化添加 cookies;如下
import requests
import parselheaders = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7','Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6','Cache-Control': 'max-age=0','Connection': 'keep-alive','Content-Type': 'application/x-www-form-urlencoded','Origin': 'https://login2.scrape.center','Referer': 'https://login2.scrape.center/login','Sec-Fetch-Dest': 'document','Sec-Fetch-Mode': 'navigate','Sec-Fetch-Site': 'same-origin','Sec-Fetch-User': '?1','Upgrade-Insecure-Requests': '1','User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0','sec-ch-ua': '"Not/A)Brand";v="8", "Chromium";v="126", "Microsoft Edge";v="126"','sec-ch-ua-mobile': '?0','sec-ch-ua-platform': '"Windows"',
}data = {'username': 'admin','password': 'admin',
}# 構(gòu)建 session
session = requests.Session()# 發(fā)送登入請(qǐng)求
response = session.post('https://login2.scrape.center/login', headers=headers, data=data, allow_redirects=False)# 無(wú)需手動(dòng)配置 cookies,發(fā)送頁(yè)面請(qǐng)求
response = session.get('https://login2.scrape.center/', headers=headers)# 解析網(wǎng)頁(yè)數(shù)據(jù)
selector = parsel.Selector(response.text)
names = selector.xpath('//*[@id="index"]/div[1]/div[1]/div/div/div/div[2]/a/h2/text()').getall()# 打印名字
print(names)# ['霸王別姬 - Farewell My Concubine',
# '這個(gè)殺手不太冷 - Léon',
# '肖申克的救贖 - The Shawshank Redemption',
# '泰坦尼克號(hào) - Titanic',
# '羅馬假日 - Roman Holiday',
# '唐伯虎點(diǎn)秋香 - Flirting Scholar',
# '亂世佳人 - Gone with the Wind',
# '喜劇之王 - The King of Comedy',
# '楚門(mén)的世界 - The Truman Show',
# '獅子王 - The Lion King']
這里是對(duì)于請(qǐng)求未涉及到加密或者帶有驗(yàn)證碼的網(wǎng)站,如果涉及到加密但是又不會(huì)解密,我們可以使用自動(dòng)化工具來(lái)獲取 Cookie;這里以 Playwright 為例子;
import requests
import parsel
from playwright.sync_api import sync_playwrightdef get_cookies():with sync_playwright() as playwright:cookies = {}browser = playwright.chromium.launch(headless=True)context = browser.new_context()page = context.new_page()page.goto("https://login2.scrape.center/login")page.locator('input[name="username"]').fill("admin")page.locator('input[name="password"]').fill("admin")page.locator('input[type="submit"]').click()cookieList = context.cookies()context.close()browser.close()for cookie in cookieList:cookies[cookie['name']] = cookie['value']return cookiesheaders = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7','Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6','Cache-Control': 'max-age=0','Connection': 'keep-alive','Content-Type': 'application/x-www-form-urlencoded','Origin': 'https://login2.scrape.center','Referer': 'https://login2.scrape.center/login','Sec-Fetch-Dest': 'document','Sec-Fetch-Mode': 'navigate','Sec-Fetch-Site': 'same-origin','Sec-Fetch-User': '?1','Upgrade-Insecure-Requests': '1','User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0','sec-ch-ua': '"Not/A)Brand";v="8", "Chromium";v="126", "Microsoft Edge";v="126"','sec-ch-ua-mobile': '?0','sec-ch-ua-platform': '"Windows"',
}cookies = get_cookies()
response = requests.get('https://login2.scrape.center/', cookies=cookies, headers=headers)# 解析網(wǎng)頁(yè)數(shù)據(jù)
selector = parsel.Selector(response.text)
names = selector.xpath('//*[@id="index"]/div[1]/div[1]/div/div/div/div[2]/a/h2/text()').getall()# 打印名字
print(names)# ['霸王別姬 - Farewell My Concubine',
# '這個(gè)殺手不太冷 - Léon',
# '肖申克的救贖 - The Shawshank Redemption',
# '泰坦尼克號(hào) - Titanic',
# '羅馬假日 - Roman Holiday',
# '唐伯虎點(diǎn)秋香 - Flirting Scholar',
# '亂世佳人 - Gone with the Wind',
# '喜劇之王 - The King of Comedy',
# '楚門(mén)的世界 - The Truman Show',
# '獅子王 - The Lion King']
五、基于JWT 的模擬登錄爬取實(shí)戰(zhàn)
目標(biāo)網(wǎng)址:Scrape | Movie

賬號(hào):admin
密碼:admin
import requestsheaders = {"Accept": "application/json, text/plain, */*","Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6","Connection": "keep-alive","Content-Type": "application/json;charset=UTF-8","Origin": "https://login3.scrape.center","Sec-Fetch-Dest": "empty","Sec-Fetch-Mode": "cors","Sec-Fetch-Site": "same-origin","User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0","sec-ch-ua": '"Not/A)Brand";v="8", "Chromium";v="126", "Microsoft Edge";v="126"',"sec-ch-ua-mobile": "?0","sec-ch-ua-platform": '"Windows"',
}json_data = {"username": "admin","password": "admin",
}# 這里使用 json 而不是使用 data 傳參是因?yàn)?headers 中的 Content-Type 接受的是 application/json 數(shù)據(jù)
response = requests.post("https://login3.scrape.center/api/login", headers=headers, json=json_data
)# 獲取 token 構(gòu)建 headers 中的 Authorization
token = response.json()["token"]
Authorization = "jwt " + token
headers = {"Accept": "application/json, text/plain, */*","Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6","Authorization": Authorization,"Connection": "keep-alive","Sec-Fetch-Dest": "empty","Sec-Fetch-Mode": "cors","Sec-Fetch-Site": "same-origin","User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0","sec-ch-ua": '"Not/A)Brand";v="8", "Chromium";v="126", "Microsoft Edge";v="126"',"sec-ch-ua-mobile": "?0","sec-ch-ua-platform": '"Windows"',
}params = {"limit": "18","offset": "0",
}# 直接使用 get 請(qǐng)求獲取數(shù)據(jù)
response = requests.get("https://login3.scrape.center/api/book", params=params, headers=headers
)print(response.json())# {
# "count": 9200,
# "results": [
# {
# "id": "34473697",
# "name": "R數(shù)據(jù)科學(xué)實(shí)戰(zhàn):工具詳解與案例分析",
# "authors": ["劉健", "鄔書(shū)豪"],
# "cover": None,
# }
# ],
# }
在這里由于使用的是 JWT,響應(yīng)頭中并不會(huì)返回一個(gè) Set-Cookies 參數(shù),因此使用 Session 來(lái)完成 JWT 是沒(méi)有效果的,只能單個(gè)請(qǐng)求進(jìn)行構(gòu)建;