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

抓取圖書信息的網站地址爲www.packtpub.com/allpython


展現內容以下:正則表達式




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


審查元素能夠看出頁面結構以下:編碼




能夠經過查找"book-block-title"定位標題,這裏用到find_all()方法,這樣就能夠找到全部書的標題,它們構成了一個列表。而後循環查找書的價格。注意到書的價格獨立於任何標籤以外,因此運用到了上篇文章講到的正則表達式匹配進行查找。url

注:這裏遇到了一個問題,我用NOTEPAD運行我寫的代碼時,報UnicodeEncodeError錯誤,用了不少方法未果。而後用Python自帶的IDLE運行程序,一次經過,知道是編碼問題,但不知道怎麼解決,暫且放下。並且發現爬取信息的時候很慢,覺得是BeautifulSoup問題,結果加入時間模塊檢測,發現是網頁打開佔去了大部分時間,爬取信息仍是蠻快的。code


下面是示例代碼:regexp

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,暫時只能作這麼多。之後學多了,能爬取的信息就更多了。ip

相關文章
相關標籤/搜索