最近有人反映淘寶的搜索功能要登錄才能用,原先的直接爬取的方法掛了。稍微把之前的代碼修改了一下,登錄采用最簡單的復制cookie來解決。
順便說一下,這只是根據搜索的的索引界面獲取的信息,並未深入的獲取每個具體商品的信息。為了以后有拓展空間,便於爬取詳細的商品信息,我順便把詳情頁的URL拿下來了。
淘寶的頁面其實並未做多大改變(吐槽一下:淘寶的程序員也挺懶的),之前的代碼只要加上登錄功能就能使用。
直接上代碼:
import requests from bs4 import BeautifulSoup import re from xlwt import Workbook import xlrd import sys R = requests.Session() URL = "https://s.taobao.com/search?q=" """ Get_Html()函數功能:根據搜索的關鍵字和頁數信息,獲取包含數據的HTML源碼 參數: keyword:字符串,搜索的關鍵字 page:字符串,頁數 返回值: text:字符串,包含數據的HTML源碼 """ def Get_Html(keyword,page): url = URL+keyword+"&ie=utf8&s="+str(page) cookies = {} raw_cookies = #這里copy你的cookie,我自然不可能放我的 for lies in raw_cookies.split(';'): key,word = lies.split('=',1) cookies[key] = word res = R.get(url,cookies = cookies) text = res.text return text """ Get_Data()函數功能:從包含數據的HTML源碼中解析出需要的數據 參數: text:字符串,是一些包含數據的HTML源碼 返回值: data:字符串,包含需要數據的json字符串 """ def Get_Data( text): reg = r',"data":{"spus":\[({.+?)\]}},"header":' reg = re.compile(reg) data = re.findall(reg, text)[0] return data """ Download_Data()函數功能:將獲取的數據選擇一部分寫入excel表格,如果想寫入數據庫,這部分代碼需要自己寫 參數: data:包含數據的json字符串 N:寫入excel表的第幾行 sheet:excel表的一張表的句柄 """ def Download_Data( data, N, sheet ): Date = eval(data) for d in Date: sheet.write(N,0,d['title']) sheet.write(N,1,d['price']) sheet.write(N,2," ".join([t['tag'] for t in d['tag_info']])) sheet.write(N,3,d['url'][2:]) N = N + 1 return N """ 主調函數,函數工作流程大致如下: 1.創建存儲數據需要的sheet表格,目前只獲取四個個特征:手機名、價格、特點和商品鏈接 2.按照關鍵字進行搜索,然后將獲得的數據全部存入創建好的sheet中。 參數: keyword:要搜索的關鍵字 """ def main(keyword): book = Workbook() sheet = book.add_sheet(keyword) sheet.write(0,0,'品牌') sheet.write(0,1,'價格') sheet.write(0,2,'特點') sheet.write(0,3,'鏈接') book.save('淘寶數據.xls') k = 0 N = 1 i = 0 while(True): text = Get_Html(keyword,i*48) try: data = Get_Data(text) N = Download_Data(data,N,sheet) except: break book.save('淘寶數據.xls') print('下載第' + str(i+1) + '頁完成') i = i + 1 print('全部數據收集完成') if __name__ == '__main__': keyword = sys.argv[1] main(keyword)
只要把上面的Get_HTML()函數中的 raw_cookies 修改成你的 cookie 就可以了,至於怎么獲取 cookie ,Google吧!
下面是我以"華為手機"為關鍵字的部分搜索結果:
發現了一個17塊的華為手機,復制鏈接一看:
果然...
上面這個頁面的信息和評論信息才是更有用的數據,以后有時間再看弄不弄吧!