日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python爬虫爬取当当网的商品信息

發布時間:2024/3/7 python 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python爬虫爬取当当网的商品信息 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

python爬蟲爬取當當網的商品信息

  • 一、環境搭建
  • 二、簡介
  • 三、當當網網頁分析
    • 1、分析網頁的url規律
    • 2、解析網頁html頁面
        • 書籍商品html頁面解析
        • 其他商品html頁面解析
  • 四、代碼實現

一、環境搭建

使用到的環境:

  • python3.8.0
  • requests庫
  • re庫
  • bs4庫
  • pycharm

二、簡介

代碼實現了根據設定的關鍵字keyword獲取相關商品的資源定位符(url),然后批量爬取相關頁面的商品信息,另外之所以選擇當當網是因為當當網的網頁商品信息不是動態加載的,因此可以直接爬取獲得,例如京東、拼多多的網頁就是動態加載的,博主暫時還不會解析動態加載的頁面😅😅😅

三、當當網網頁分析

1、分析網頁的url規律

首先是分析出當當網的搜索商品的url,瀏覽器進入當當網主頁,在檢索欄輸入任意的商品關鍵詞,可以看到打開的頁面的url鏈接形式為如下形式:

url = 'http://search.dangdang.com/?key={}&act=input'.format(keyword)

然后獲取頁面翻頁可以發現這類商品的每一頁的url形式為:

url = "http://search.dangdang.com/?key={}&input&page_index={}".format(keyword,page_count)

分析出了這些規律之后,就可以根據輸入的關鍵詞自動生成相應頁面的url,然后像服務器發送請求,得到每頁的html信息。

2、解析網頁html頁面

瀏覽器打開任一網頁,打開網頁調試工具可以發現,當當網的商品網頁分為兩類(很奇葩),第一類是書籍類商品的網頁,第二類是其他商品。

書籍商品html頁面解析

經過調試發現,頁面的商品信息都在ul標簽下的中li標簽中,每個li標簽塊存放一個商品的所有信息,商品的一些信息例如namepriceauthor等信息又存放在li標簽下對應的p標簽中,因此解析每個p標簽的相關屬性信息,就能獲得對應的信息。值得一提的是書籍商品頁面的ul標簽的class屬性是"bigmig"。

其他商品html頁面解析

其他商品和書籍類商品的商品信息存放的標簽塊基本相同,唯一不同的是其ul標簽的class屬性是"bigimg cloth_shoplist",解析類似,只不過要區別得到的ul標簽的class屬性。

四、代碼實現

代碼主要包括四個函數:

def getMaxPageCount(keyword):# 爬取商品的最大頁面數try:user_agent = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'}max_page_count = 0url = 'http://search.dangdang.com/?key={}&act=input'.format(keyword)rspon = requests.get(url, headers = user_agent)rspon.encoding = rspon.apparent_encodingrspon.raise_for_status()except:print("爬取頁數失敗:", rspon.status_code)return max_page_counthtml = BeautifulSoup(rspon.text, "html.parser")ul_tag = html.find('ul', {"name":"Fy"})for child in ul_tag.children:if type(child) == type(ul_tag):match = re.match(r"\d+",str(child.string))if match:temp_num = int(match.group(0))if temp_num > max_page_count:max_page_count = temp_numreturn max_page_count

getMaxPageCount(keyword) 函數主要是根據輸入的商品種類關鍵詞爬取相應的網頁,獲取當前種類商品的最大頁數。

def getOnePageMsg(product_list, url):# 爬取一個頁面的商品數據try:user_agent = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'}rspon = requests.get(url, headers = user_agent)rspon.encoding = rspon.apparent_encodingrspon.raise_for_status()except:print("爬取頁數失敗:", rspon.status_code)html = BeautifulSoup(rspon.text, "html.parser")ul_tag = html.find('ul', {"class": "bigimg cloth_shoplist"})if ul_tag:search_type = 2else:ul_tag = html.find('ul', {"class": "bigimg"})if ul_tag:search_type = 1else:returnif search_type ==1:for child in ul_tag.children:if type(child) == type(ul_tag):temp_list = []# 保存書名tag_name = (child.find('p',{"class":"name"})).find('a')temp_list.append(str(tag_name.attrs["title"]))# 保存價格tag_price = (child.find('p',{"class":"price"})).find("span", {"class":"search_now_price"})temp_list.append(str(tag_price.string))# 保存作者tag_author = child.find('p', {"class":"search_book_author"}).find('a',{"name":"itemlist-author"})if tag_author:temp_list.append(str(tag_author.string))else:temp_list.append(str("NULL"))# 保存出版社tag_pub = child.find('p', {"class": "search_book_author"}).find('a', {"name": "P_cbs"})if tag_pub:temp_list.append(str(tag_pub.string))else:temp_list.append(str("NULL"))#保存評價tag_comment = child.find('p',{"class":"search_star_line"}).find('a')temp_list.append(str(tag_comment.string))product_list.append(temp_list)else:for child in ul_tag.children:if type(child) == type(ul_tag):temp_list = []# 保存商品名tag_name = (child.find('p',{"class":"name"})).find('a')temp_list.append(str(tag_name.attrs["title"]))# 保存價格tag_price = (child.find('p',{"class":"price"})).find("span")temp_list.append(str(tag_price.string))#保存評價tag_comment = child.find('p',{"class":"star"}).find('a')temp_list.append(str(tag_comment.string))product_list.append(temp_list)

getOnePageMsg(product_list, url) 函數實現的是根據一個url爬取網頁的html信息,然后解析信息得到需要的商品信息,主要是使用bs4庫的BeautifulSoup解析網頁結構,并且將數據存入product_list列表中。

def getAllPageMsg(keyword, product_list):# 爬取商品的所有頁面的數據page_count = getMaxPageCount(keyword)print("find ",page_count," pages...")for i in range(1,page_count+1):url = "http://search.dangdang.com/?key={}&input&page_index={}".format(keyword,i)getOnePageMsg(product_list,url)print(">> page",i," import successfully...")

getAllPageMsg(keyword, product_list) 函數實現的是根據關鍵詞首先獲取這一商品的最大頁面,然后自動化生成每一個頁面的url,在調用getOnePageMsg函數解析每個url頁面,得到數據列表product_list。

def writeMsgToFile(path,keyword,product_list):# 將爬取的數據保存到文件file_name = "{}.txt".format(keyword)file = open(path+file_name, "w", encoding='utf-8')for i in product_list:for j in i:file.write(j)file.write(' ')file.write("\n")file.close()

writeMsgToFile(path,keyword,product_list) 函數主要實現將列表的數據寫入文件,當然還有根據傳入的路徑和關鍵字生成對應的文件名。

def main():# 函數入口keyword = 'python'path="E://"product_list = []getAllPageMsg(keyword,product_list)writeMsgToFile(path,keyword,product_list)

最后main()函數是實現方法的入口,包括一些參數的初始化設置。
執行main()函數就能實現網頁數據的爬取,以下是以python為關鍵詞,爬取頁面得到的結果,抓取解析完所有頁面花了3分鐘左右。



可以看到最終生成的txt文件一共有6000行,每一行保存的就是商品的信息。

總結

以上是生活随笔為你收集整理的python爬虫爬取当当网的商品信息的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。