1. 程式人生 > >Learn Beautiful Soup(4)—— 一個簡單抓取圖書資訊的例子

Learn Beautiful Soup(4)—— 一個簡單抓取圖書資訊的例子

展示內容如下:


我們的目的很簡單——獲取當前頁每本書的名字和價格。

審查元素可以看出頁面結構如下:


可以通過查詢"book-block-title"定位標題,這裡用到find_all()方法,這樣就可以找到所有書的標題,它們構成了一個列表。然後迴圈查詢書的價格。注意到書的價格獨立於任何標籤之外,所以運用到了上篇文章講到的正則表示式匹配進行查詢。

注:這裡遇到了一個問題,我用NOTEPAD執行我寫的程式碼時,報UnicodeEncodeError錯誤,用了很多方法未果。然後用Python自帶的IDLE執行程式,一次通過,知道是編碼問題,但不知道怎麼解決,暫且放下。而且發現爬取資訊的時候很慢,以為是BeautifulSoup問題,結果加入時間模組檢測,發現是網頁開啟佔去了大部分時間,爬取資訊還是蠻快的。

下面是示例程式碼:

import urllib.request
import datetime
import re

from bs4 import BeautifulSoup

starttime = datetime.datetime.now()

url = "https://www.packtpub.com/all"
page = urllib.request.urlopen(url)
soup_packtpage = BeautifulSoup(page)
page.close()

endtime = datetime.datetime.now()
print (endtime - starttime)

starttime = datetime.datetime.now()

all_book_title = soup_packtpage.find_all("div", class_="book-block-title")


price_regexp = re.compile(u"\s+£\s\d+\.\d+")

for book_title in all_book_title:
	print("Book's name is " + book_title.string.strip())
	book_price = book_title.find_next(text=price_regexp)
	print("Book's price is "+ book_price.strip())
	print("\n")
	
endtime = datetime.datetime.now()

print (endtime - starttime)

輸出:


關於圖書的資訊還有很多,比如圖書大概內容,圖書的ISBN號,圖書頁數等,這些需要跳轉到另一個頁面去獲取。目前初學了一點BeautifulSoup,暫時只能做這麼多。以後學多了,能爬取的資訊就更多了。