1. 程式人生 > >豆瓣爬取圖書標籤

豆瓣爬取圖書標籤

這是我第一個全程自己動手做的專案,算得上是中小型的吧。網上看到好多關於python爬蟲的專案,說是找工作必會,但我都感覺有些難。最後不管三七二十一,試試再說,做不出來也不會損失什麼。於是選了一個豆瓣圖書標籤爬取的專案,github(用過好多次了,但不太瞭解,感覺就是一個讓程式設計師分享成果的一個平臺)上有原始碼,但是沒有一句註釋。

終於,我花了兩天的時間給整出來了,感覺非常欣慰,沒想到會這麼快。以前看視訊學習都得兩天才能大致瞭解一個專案,可能是現在自己的知識儲備積累多了吧^_^

最重要的是,通過自己做專案,能夠彌補好多以前自己不紮實的基本功,比如正則表示式,urllib, BeautifulSoup, MongoDB,以前都是跟著視訊做專案使用過,也全面講解過,但沒有自己動手練習,非常的不熟練。還有對於如何儲存到Excel, 如何使儲存到excel中的標籤按順序排列,都是通過這個專案學到的。

不費話了,進入正題,這個專案要求是:1. 從豆瓣爬取相關圖書標籤; 2. 將不同種類的圖書列為幾個不同的列表,將各自種類的圖書標籤存進去; 3. 沒有IP代理池,採用了延時的笨方法。

直接上程式碼:

import requests
import re
import xlwt
import time
import random
from requests.exceptions import RequestException

def do_spider(book_tag_lists):
    book_lists=[]
    for book_tag in book_tag_lists:
        book_list
=book_spider(book_tag) book_lists.append(book_list) return book_lists def book_spider(book_tag): page_num = 0 book_list = [] try_times = 0 while (page_num<10): url = 'https://book.douban.com/tag/'+ book_tag + '?start='+ str(page_num * 20) time.sleep(random.uniform(0,
3)) # 0 到 5 之間的隨機浮點數 # time.sleep(random.randint(0,5)) 0 到 5 之間的隨機整數,包括0,5 try: 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', 'Accept - Language': 'zh - CN, zh;q = 0.9' } # 加上headers,網站認為是瀏覽器訪問,就能爬取 response = requests.get(url, headers=headers) if response.text: # 這5行程式碼是為了爬取每種型別的所有得書使用的 response_text = response.text else: try_times+=1 continue except RequestException: return None # if try_times > 200:break # 在這兒使用了while (page_num<10)來退出 pattern = re.compile('<li.*?<a.*?title="(.*?)".*?<div.*?pub">(.*?)</div>.*?' '"rating_nums">(.*?)</span>.*?</li>', re.S) items = re.findall(pattern, response_text) # 從網頁中提取相關的標籤 for item in items: other = item[1].strip() other_2 = other.split('/') # 把字串通過'/'符號拆分為一個列表 title = item[0] author = other_2[0].strip() date = other_2[-2].strip() rating_nums = item[2] print(title,author,date,rating_nums) book_list.append([title, author, date, rating_nums]) try_times = 0 page_num += 1 print('Downloading Information From Page_' + str(page_num)) return book_list # 將爬取得內容寫到Excel中 def print_book_list_excel(book_lists, book_tag_lists): wb = xlwt.Workbook(encoding='utf-8') for i in range(len(book_tag_lists)): ws = wb.add_sheet(book_tag_lists[i]) ws.write(0, 1, '標題') ws.write(0, 2, '作者') ws.write(0, 3, '出版日期') ws.write(0, 4, '評分') count = 0 for bl in book_lists[i]: count+=1 ws.write(count,0,count) for j in range(4): ws.write(count,j+1,bl[j]) wb.save('excel.xls') def main(): book_tag_lists = ['小說','漫畫','歷史','經濟學','網際網路'] book_lists = do_spider(book_tag_lists) # 已經呼叫過book_spider了 print_book_list_excel(book_lists,book_tag_lists) if __name__ == '__main__': main()

專案製作流程:1.先按照以前的經驗,爬取了“小說”的10頁圖書標籤,並寫在文字文件中。(中間遇到許多挫折,尤其是正則表示式這塊)

       2. 文字文件的內容不是按照“標題”、“作者”、“出版日期”、“評分”的順序來排列的,而是亂序(因為for迴圈從字典中讀資料本來就是亂序)。

        於是看了下載的程式碼,採用了 book_list.append([title, author, date, rating_nums]) 來代替字典形式(因為for迴圈從列表中讀資料是按順序來的)。

       3. 將其寫入Excel表格,先用了下載的程式碼方法,不管用,只有sheet表格,沒有寫入的內容。網上查了一些方法,結合下載的程式碼,就實現了。

       4. 最後改寫程式碼為每個種類的圖書建一個sheet表格。