本文爬取內(nèi)容,輸入要搜索的關(guān)鍵字可自動爬取京東網(wǎng)站上相關(guān)商品的店鋪名稱,商品名稱,價格,爬取100頁(共100頁)
代碼如下;
import requests import re # 請求頭 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36' } def get_all(url,key): for page in range(1,200,2): params = { 'keyword':key, 'enc':'utf-8', 'page':page } num = int((int(page)+1)/2) try: response = requests.get(url=url,params=params,headers=headers) # 轉(zhuǎn)碼 content = response.text.encode(response.encoding).decode(response.apparent_encoding) data_all = re.findall('<div class="p-price">.*?<i>(.*?)</i>.*?<div class="p-name p-name-type-2">.*?title="(.*?)"' '.*?<div class="p-shop".*?title="(.*?)"',content,re.S) for i in data_all: with open(key + '.txt', 'a+', encoding='utf-8') as f: f.write('店鋪名稱:' + i[2]+'n'+'商品名稱:'+i[1]+'n'+'價格:'+i[0]+'nn') print('第'+str(num)+'頁'+'數(shù)據(jù)下載中....') except Exception as e: print(e) if __name__ == '__main__': print('輸入要搜索的內(nèi)容,獲取京東商城里面的商品名稱,店鋪名稱,商品價格') key = input('輸入搜索內(nèi)容:') url = 'https://search.jd.com/Search?' get_all(url,key)
打包成.exe可執(zhí)行文件。
需要用到pyinstaller包pip下載;
pip install pyinstaller
在線制作一個.ico圖標(biāo),用來當(dāng)程序圖片,把圖標(biāo)和程序放在同一個文件夾下,
在.py文件目錄下打開命令行窗口,執(zhí)行打包命令;
E:練習(xí)最后階段