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

歡迎訪問 生活随笔!

生活随笔

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

python

Python 爬虫分析豆瓣 TOP250 之 信息字典 和 马斯洛的锥子

發布時間:2023/12/14 python 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python 爬虫分析豆瓣 TOP250 之 信息字典 和 马斯洛的锥子 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

問題

本文是對《Python 爬蟲分析豆瓣 TOP250 告訴你程序員業余該看什么書?》 一文的補充

我們以《追風少年》為例


用chrome的developer tool查看源代碼

這里發現,源代碼的HTML比較難以分析(Parse)。

在原作者的文中,把這些都放在了一起。

[美] 卡勒德·胡賽尼 / 李繼宏 / 上海人民出版社 / 2006-5 / 29.00元

而這樣并不能滿足我的要求(知識圖譜)。

一開始,我也嘗試著用xpath里面的sibling, next等去抓信息,但是都失敗了。后來恍然大悟。其實,如果單單從頁面上看,這明明就是key value pair,用冒號隔開。于是,我直接把字符串抓出來,很容易就搞定了。

信息字典

理想情況下,抓出來的信息是這個樣子的。

作者: [美] 卡勒德·胡賽尼 出版社: 上海人民出版社 出品方: 世紀文景 原作名: The Kite Runner 譯者: 李繼宏 出版年: 2006-5 頁數: 362 定價: 29.00元 裝幀: 平裝 叢書: 卡勒德·胡賽尼作品 ISBN: 9787208061644

這樣,一行行分析就行了。

但實際上,抓出來的信息是這樣的

作者: [美]卡勒德·胡賽尼出版社: 上海人民出版社 出品方: 世紀文景 原作名: The Kite Runner 譯者: 李繼宏出版年: 2006-5 頁數: 362 定價: 29.00元 裝幀: 平裝 叢書: 卡勒德·胡賽尼作品 ISBN: 9787208061644

不過,也沒關系,用正則表達式抓到所有的key。這樣key之間的就是value了。

具體代碼如下。(python 3.7)

# -*- coding: utf-8 -*- """ Created on Wed Feb 27 12:08:08 2019@author: eric """import requests from lxml import etree from bs4 import BeautifulSoup import time import reclass Douban_Book():url = ""title_cn=""title_original="" #原作名author=""author_profile = ""publisher="" #出版社publish_date=""pages=""price=""series=""isbn=""rating = 0.0votes = 0summary = ""HEADERS = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}def get_urls():#https://book.douban.com/top250?start=225url_base = "https://book.douban.com/top250?start="urls = [url_base+str(i*25) for i in range(10)]return urlsdef get_dict_value(the_dict, key, defualt_value=""):if key in the_dict:return the_dict[key]return defualt_valuedef get_book(book_url):response = requests.request("get", book_url, headers=HEADERS)soup = BeautifulSoup(response.text, "html.parser")book = Douban_Book()book.url = book_urlbook.title_cn = soup.find("h1").text.strip()#以下是信息字典soup_info = soup.find("div",{"id":"info"})info_text = soup_info.textheads = re.findall("\n.+:",info_text)info_dict = {}for i in range(len(heads)-1):start_at=info_text.find(heads[i])+len(heads[i])end_at=info_text.find(heads[i+1])value = info_text[start_at:end_at].strip().replace("\n","")value = re.sub("\s+"," ",value)key = heads[i].strip().replace(":","")info_dict[key]=value#the last key value pairstart_at=info_text.find(heads[-1])+len(heads[-1])value = info_text[start_at:].strip().replace("\n","")key = heads[-1].strip().replace(":","")info_dict[key]=value#把信息字典里的信息寫入book對象book.author = get_dict_value(info_dict, "作者")book.isbn = get_dict_value(info_dict, "ISBN")book.pages = get_dict_value(info_dict, "頁數")book.price = get_dict_value(info_dict, "定價")book.publish_date = get_dict_value(info_dict, "出版年")book.publisher = get_dict_value(info_dict, "出版社")book.series = get_dict_value(info_dict, "叢書")book.title_original = get_dict_value(info_dict, "原作名")#豆瓣評分book.rating = float(soup.find("strong",{"class":"ll rating_num "}).text.strip())#<span property="v:votes">405241</span>book.votes = int(soup.find("span",{"property":"v:votes"}).text)#簡介intros = soup.find_all("div",{"class":"intro"})for p in intros[0].find_all("p"):book.summary+=p.text+"\r\n"for p in intros[1].find_all("p"):book.author_profile+=p.text+"\r\n"return bookdef save_book(book):print("saving book {0} {1}".format(book.title_cn, book.title_original))pass#https://book.douban.com/top250?start=0 def parse_list(list_url):response = requests.request("get", list_url, headers=HEADERS)tree = etree.HTML(response.text)trs=tree.xpath("//tr[@class='item']")for tr_item in trs:book_url=tr_item.xpath("descendant::a[1]/@href")[0]book = get_book(book_url)save_book(book)def main():urls = get_urls()for url in urls[:1]:parse_list(url)time.sleep(1.1)

馬斯洛的錐子

有時候,我們用慣了爬蟲工具,會陷進爬蟲工具的牛角尖里面。或者說,「如果你有的只是一個錘子,那麼所有的東西看起來都像一個釘子」 – Abraham Maslow。

總結

以上是生活随笔為你收集整理的Python 爬虫分析豆瓣 TOP250 之 信息字典 和 马斯洛的锥子的全部內容,希望文章能夠幫你解決所遇到的問題。

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