# encoding:utf-8import re # 使用正則 匹配想要的數據import requests # 使用requests得到網頁源碼
這個函數是用來得到源碼
# 得到主函數傳入的鏈接def getHtmlText(url): try: # 異常處理 # 得到你傳入的URL鏈接 設置超時時間3秒 r = requests.get(url, timeout=3) # 判斷它的http狀態碼 r.raise_for_status() # 設置它的編碼 encoding是設置它的頭部編碼 apparent_encoding是從返回網頁中分析它的編碼格式 r.encoding = r.apparent_encoding # 返回源代碼 return r.text except: # 發生異常返回空 return ''
這個函數使用來解析你的源代碼 獲取你想要的數據
# 解析你的網頁信息def parsePage(ilt, html): # 異常處理 try: # 找到書包的價格 plt = re.findall(r'/"view_price/"/:/"[/d/.]*/"', html) # 找到書包的名稱 tlt = re.findall(r'/"raw_title/"/:/".*?/"', html) # 找到書包的地址 add = re.findall(r'/"item_loc/"/:/".*?/"', html) # 找到書包的圖片鏈接 img = re.findall(r'/"pic_url/"/:/".*?/"', html) # 得到這個內容放入主函數中的列表 for i in range(len(plt)): price = eval(plt[i].split(':')[1]) title = eval(tlt[i].split(':')[1]) address = eval(add[i].split(':')[1]) imgs = eval(img[i].split(':')[1]) ilt.append([price, title, address, imgs]) except: # 放生異常輸出空字符串 print('')# 得到主函數傳入的列表def printGoodsList(ilt): # 每個列之間用tplt的放是隔開 tplt = '{:4}/t{:8}/t{:16}/t{:32}' # 這個是整個的標題 print(tplt.format('序號', '價格', '商品名稱','地址', '圖片地址')) count = 0 # 統計有多少的序號 for g in ilt: count = count + 1 # 循環一遍加一 print(tplt.format(count, g[0], g[1], g[2]), g[3]) # 輸出你得到的數據# 定義主函數 maindef 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(44 * i) # 得到你的網址 html = getHtmlText(url) # 得到url傳入到你要得到url的函數中 parsePage(infoList, html) # 得到你的html源碼 放入解析的網頁中 except: # 發生異常跳過 continue # 把列表中的數據放入解析的函數中 printGoodsList(infoList)
# 代碼調試片段if __name__ == '__main__': main() # 調用主函數
以上就是經過小編測試過的用python3爬取淘寶信息的代碼,大家測試后如果還有任何不明白的地方可以在下方的留言區討論。
新聞熱點
疑難解答