嵩天老師網絡爬蟲與信息提取課程學習筆記(三)

此文根據嵩天老師的視頻課程邊聽邊敲下來的代碼,模塊化代碼結構,將爬蟲實例的三個步驟用三個函數實現,功能見下面解釋,感謝MOOC平臺,謝謝嵩老師的精細講解,以及助教的圖文解說突破淘寶訪問限制。

#淘寶商品信息定向爬蟲
#功能描述:獲取淘寶搜索頁面的信息,提取其中的商品名稱和價格
#理解:淘寶的搜索接口
#      翻頁的處理
#技術路線:requests - re
#URL:https://s.taobao.com/search?q=%E5%8C%85&imgfile=&js=1&stats_click=search_radio_all%3A1&initiative_id=staobaoz_20200410&ie=utf8
#程序的結構設計
#步驟1:提交商品搜索請求,循環獲取頁面.
#步驟2:對於每個頁面,提取商品名稱和價格信息。
#步驟3:將信息輸出到屏幕上。
#因爲淘寶需要登錄,因此在原有程序基礎之上,加入了兩個get參數,一個是User-Agent,一個是cookie,這也是爬蟲突破封禁的其中2種常見方法.
#1.其中User-Agent就是爲了構造合理的 HTTP 請求頭,因爲python程序去訪問,請求頭中User-Agent會是一個爬蟲在使用 urllib 標準庫時發送的請求頭,如Python-urllib/3.4之類的。
#因此在代碼中指定爲瀏覽器之類的。
#2.網站會用 cookie 跟蹤你的訪問過程,如果發現了爬蟲異常行爲就會中斷你的訪問,比如這個程序爬取淘寶數據時,如果沒有設置cookie,會導致網頁獲取時轉到登錄頁面,不能正常獲取數據,
#因此需要指定這個值,調出這個值時,我是先登錄了淘寶,然後搜索指定物品,在網頁頁面上按F12,查看對應鏈接中Network菜單界面中name爲search?q=。。。這個鏈接下的headers裏的request Headers裏的cookie值。
import re
import requests
def getHTMLText(url):
	try:
		headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36",
		"cookie": "你的cookie信息,需要自己按照下方圖片去找,祝你好運!"}
		r = requests.get(url,timeout = 30,headers = headers )
		r.raise_for_status()
		r.encoding = r.apparent_encoding
		return r.text
	except :
		return ""
	

def parsePage(ilt,html):
	try:
		regex1 = re.compile(r'\"view_price\"\:\"[\d\.]*\"')
		regex2 = re.compile(r'\"raw_title\"\:\".*?\"')
		plt = regex1.findall(html)
		tlt = regex2.findall(html)
		for i in range(len(plt)):
			price = eval(plt[i].split(':')[1])
			title = eval(tlt[i].split(':')[1])

			ilt .append([price,title])
	except:
		print("parsePageEx")

def printGoodsList(ilt):
	tplt = "{:4}\t{:8}\t{:16}"
	print(tplt.format("序號","價格","商品名稱"))
	count = 0
	for g in ilt:
		count = count + 1
		print(tplt.format(count,g[0],g[1]))

def main():
	goods = "佳明"
	depth = 2
	start_url = "https://s.taobao.com/search?q=" + goods
	infoList = []
	for i in range(depth):
		try :
			url = start_url + '&s=' + str(i*44)
			
			html = getHTMLText(url)
			#print(html)
			parsePage(infoList,html)
		except:
			print("mainEx")
			continue
	printGoodsList(infoList)
main()

下圖是找cookie的方法:
在這裏插入圖片描述
下圖是程序運行部分結果截圖:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章