實例介紹
目的:獲取某種類別商品的信息,提取商品的名稱與價格
可行性分析
1.查看淘寶的robots協議,附網址https://www.taobao.com/robots.txt
查看發現淘寶不允許任何人對淘寶信息進行爬取。那么作為一名守法公民為了不要引起不必要的麻煩,
一,不要爬取,二,爬取的程序不要做任何商業用途,僅僅只能用作技術學習。
程序結構
1.請求搜索商品,循環獲取頁面
2.解析頁面內容,獲取商品價格名稱
3.輸出獲得的信息
結構分析
查看商品的數量,比如,我要查看衛衣
顯示了一百頁,那么我們查看時就要考慮查看多少了,如果是一頁,就只需要爬取一個鏈接里的信息,
如果要爬取多個頁面的信息,就需要多個鏈接了,這時就需要找到鏈接之間的關系。
第一個頁面的URL:
https://s.taobao.com/search?initiative_id=tbindexz_20170306&ie=utf8&spm=a21bo.2017.201856-taobao-item.2&sourceId=tb.index&search_type=item&ssid=s5e&commend=all&imgfile=&q=衛衣&suggest=history_1&_input_charset=utf8&wq=&suggest_query=&source=suggest&bcoffset=6&ntoffset=6&p4ppushleft=1%2C48&s=0
第二個頁面的URL:
https://s.taobao.com/search?initiative_id=tbindexz_20170306&ie=utf8&spm=a21bo.2017.201856-taobao-item.2&sourceId=tb.index&search_type=item&ssid=s5e&commend=all&imgfile=&q=衛衣&suggest=history_1&_input_charset=utf8&wq=&suggest_query=&source=suggest&bcoffset=3&ntoffset=3&p4ppushleft=1%2C48&s=44
第二個頁面的URL:
https://s.taobao.com/search?initiative_id=tbindexz_20170306&ie=utf8&spm=a21bo.2017.201856-taobao-item.2&sourceId=tb.index&search_type=item&ssid=s5e&commend=all&imgfile=&q=衛衣&suggest=history_1&_input_charset=utf8&wq=&suggest_query=&source=suggest&bcoffset=0&ntoffset=6&p4ppushleft=1%2C48&s=88
連續查看三個頁面的URL后發現,每個URL尾部s以44遞增。找到規律后,就可以用循環語句進行頁面請求了。
實例編寫
1 import requests 2 import re 3 4 def getHTMLText(url): 5 try: 6 r = requests.get(url,timeout = 30) 7 r.raise_for_status() 8 r.encoding = r.apparent_encoding 9 return r.text 10 except: 11 return "" 12 def parsePage(ilt,html): 13 #正則表達式獲取商品名稱和商品價格 14 try: 15 #使用正則表達式,\表示引入一個"view_price"的鍵,后面\引入鍵的值 16 plt = re.findall(r'\"view_price\"\:\"[\d\.]*\"',html) 17 #*?表示最小匹配 18 tlt = re.findall(r'\"raw_title\"\:\".*?\"',html) 19 for i in range(len(plt)): 20 price = eval(plt[i].split(":")[1]) 21 title = eval(tlt[i].split(":")[1]) 22 ilt.append([price,title]) 23 except: 24 print(" ") 25 def printGoodslist(ilt): 26 tplt = "{:4}\t{:8}\t{:16}" 27 print(tplt.format("序號","價格","商品名稱")) 28 count = 0 29 for x in ilt: 30 count = count + 1 31 print(tplt.format(count,x[0],x[1])) 32 def main(): 33 goods = '衛衣' 34 depth = 2 35 star_url = 'https://s.taobao.com/search?q=' +goods 36 infoList = [] 37 for i in range(depth): 38 try: 39 url = star_url + '&s=' + str(44*i) 40 html = getHTMLText(url) 41 parsePage(infoList,html) 42 except: 43 continue 44 printGoodslist(infoList) 45 main()
編譯運行后發現程序並沒有報錯,但沒有出現商品的輸出信息,着實讓人摸不着頭腦。於是在百度幫助下,
我先是檢查自己的URL是不是正確的,復制程序中的URL在瀏覽器打開,發現可以進入淘寶,URL是正確的。
不是URL的問題,那就是淘寶的問題了,原來淘寶設置反爬蟲機制,需要用戶登錄驗證。爬取時需要模擬瀏
覽器登錄才能獲取信息。
1.瀏覽器打開淘寶,登錄
2.搜索框搜索自己想要爬取的東西,例如衛衣,按F12打開開發者工具
3.選中網絡,再選中doc文件
4.回到淘寶首頁,開發者工具不要關閉!
刷新出如圖的一個文件
5.打開文件,找到cookie和user-agent,將里面的內容完全復制下來
最后在原來的代碼寫一個headers字典模擬瀏覽器請求訪問,放入剛才復制的cookie和user-agent
全代碼:
1 import requests 2 import re 3 4 def getHTMLText(url): 5 headers={'cookie':'td_cookie=18446744071423230592; thw=cn; v=0; cna=SCVpFkZXfCwCAT24cx3PJgie; t=6adef129ce0b98c6fcd52f3e83e3be03; cookie2=7de44eefb19e3e48e25b7349163592b7; _tb_token_=f1fae43e5e551; unb=3345403123; uc3=nk2=F6k3HMt8ZHbGobgMG0t6YMg7MKU%3D&vt3=F8dByuQFmIAq493a88Y%3D&lg2=W5iHLLyFOGW7aA%3D%3D&id2=UNN5FEBc3j%2FI9w%3D%3D; csg=07879b0c; lgc=t_1499166546318_0384; cookie17=UNN5FEBc3j%2FI9w%3D%3D; dnk=t_1499166546318_0384; skt=759aebdc118b2fc5; existShop=MTU3NTEwNzAyMg%3D%3D; uc4=id4=0%40UgQxkzEr7yNNkd0wQjAOQOK5hAra&nk4=0%40FbMocp0bShNOwIAboxPdw7pZW0Ru%2FnrngZiTM4a03Q%3D%3D; tracknick=t_1499166546318_0384; _cc_=UIHiLt3xSw%3D%3D; tg=0; _l_g_=Ug%3D%3D; sg=439; _nk_=t_1499166546318_0384; cookie1=B0TwtzQNNmewbhSpcaaRe7U24nc6DXOpwhexZLEN8Zo%3D; mt=ci=0_1; _m_h5_tk=ec0a32b82d6a8d5c46fe6f873373169b_1575114952532; _m_h5_tk_enc=cfea89ad4f02b520c3a094931d00e376; enc=CnjhIlaGaoA3J%2FSi2PeXU8%2FNC4cXQUAZjulyZI%2Bd9Z8JjGflldsE%2F%2B8F0Ty2oLD4v1wKgm3CuiGftr11IfyB5w%3D%3D; hng=CN%7Czh-CN%7CCNY%7C156; l=dBIBcdfeq5nSzFl5BOCa-urza77ThIRvfuPzaNbMi_5Ia1T6YV7OknJtce96cjWfTG8B4HAa5Iy9-etlwrZEMnMgcGAw_xDc.; uc1=cookie15=VFC%2FuZ9ayeYq2g%3D%3D&cookie14=UoTbmEp9zNxMrw%3D%3D; isg=BDk53DNPQMq9RRxe_Fnoei4wSKUTRi34hR8HPVturmDf4ll0o5Y9yKc0YOYUrsUw', 6 'user-agent':'Mozilla/5.0'} 7 try: 8 r = requests.get(url,headers = headers,timeout = 30) 9 r.raise_for_status() 10 r.encoding = r.apparent_encoding 11 return r.text 12 except: 13 return "" 14 def parsePage(ilt,html): 15 #正則表達式獲取商品名稱和商品價格 16 try: 17 #使用正則表達式,\表示引入一個"view_price"的鍵,后面\引入鍵的值 18 plt = re.findall(r'\"view_price\"\:\"[\d\.]*\"',html) 19 #*?表示最小匹配 20 tlt = re.findall(r'\"raw_title\"\:\".*?\"',html) 21 for i in range(len(plt)): 22 price = eval(plt[i].split(":")[1]) 23 title = eval(tlt[i].split(":")[1]) 24 ilt.append([price,title]) 25 except: 26 print(" ") 27 def printGoodslist(ilt): 28 tplt = "{:4}\t{:8}\t{:16}" 29 print(tplt.format("序號","價格","商品名稱")) 30 count = 0 31 for x in ilt: 32 count = count + 1 33 print(tplt.format(count,x[0],x[1])) 34 def main(): 35 goods = '衛衣' 36 depth = 2 37 star_url = 'https://s.taobao.com/search?q=' +goods 38 infoList = [] 39 for i in range(depth): 40 try: 41 url = star_url + '&s=' + str(44*i) 42 html = getHTMLText(url) 43 parsePage(infoList,html) 44 except: 45 continue 46 printGoodslist(infoList) 47 main()
在headers字典時,程序一直報錯,報錯在user-agent后面的冒號上,弄了很長時間不得解,百度也沒辦法
最后才想起寫字典時中間的鍵值對沒有給英文逗號,令人啼笑皆非。
最后的編譯結果: