Python3網絡爬蟲(七):使用Beautiful Soup爬取小說


一、Beautiful Soup簡介

    簡單來說,Beautiful Soup是python的一個庫,最主要的功能是從網頁抓取數據。官方解釋如下:

  • Beautiful Soup提供一些簡單的、python式的函數用來處理導航、搜索、修改分析樹等功能。它是一個工具箱,通過解析文檔為用戶提供需要抓取的數據,因為簡單,所以不需要多少代碼就可以寫出一個完整的應用程序。

  • Beautiful Soup自動將輸入文檔轉換為Unicode編碼,輸出文檔轉換為utf-8編碼。你不需要考慮編碼方式,除非文檔沒有指定一個編碼方式,這時,Beautiful Soup就不能自動識別編碼方式了。然后,你僅僅需要說明一下原始編碼方式就可以了。

  • Beautiful Soup已成為和lxml、html6lib一樣出色的python解釋器,為用戶靈活地提供不同的解析策略或強勁的速度。

    廢話不多說,直接開始動手吧!

二、實戰

1.背景介紹

    小說網站-筆趣看: 
    URL:http://www.biqukan.com/

    筆趣看是一個盜版小說網站,這里有很多起點中文網的小說,該網站小說的更新速度稍滯后於起點中文網正版小說的更新速度。並且該網站只支持在線瀏覽,不支持小說打包下載。因此,本次實戰就是從該網站爬取並保存一本名為《一念永恆》的小說,該小說是耳根正在連載中的一部玄幻小說。PS:本實例僅為交流學習,支持耳根大大,請上起點中文網訂閱。

2.Beautiful Soup安裝

    我們我可以使用pip3或者easy_install來安裝,在cmd命令窗口中的安裝命令分別如下:

a)pip3安裝

pip3 install beautifulsoup4
  • 1

b)easy_install安裝

easy_install beautifulsoup4
  • 1

3.預備知識

    更為詳細內容,可參考官方文檔: 
    URL:http://beautifulsoup.readthedocs.io/zh_CN/latest/

a)創建Beautiful Soup對象

from bs4 import BeautifulSoup

#html為解析的頁面獲得html信息,為方便講解,自己定義了一個html文件

html = """
<html> <head> <title>Jack_Cui</title> </head> <body> <p class="title" name="blog"><b>My Blog</b></p> <li><!--注釋--></li> <a href="http://blog.csdn.net/c406495762/article/details/58716886" class="sister" id="link1">Python3網絡爬蟲(一):利用urllib進行簡單的網頁抓取</a><br/> <a href="http://blog.csdn.net/c406495762/article/details/59095864" class="sister" id="link2">Python3網絡爬蟲(二):利用urllib.urlopen發送數據</a><br/> <a href="http://blog.csdn.net/c406495762/article/details/59488464" class="sister" id="link3">Python3網絡爬蟲(三):urllib.error異常</a><br/> </body> </html> """ #創建Beautiful Soup對象 soup = BeautifulSoup(html,'lxml')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

    如果將上述的html的信息寫入一個html文件,打開效果是這樣的(<!–注釋–>為注釋內容,不會顯示):

 

 

 

 

    同樣,我們還可以使用本地HTML文件來創建對象,代碼如下:

soup = BeautifulSoup(open(test.html),'lxml')
  • 1

    使用如下代碼格式化輸出:

print(soup.prettify())
  • 1

 

 

 

 

b)Beautiful Soup四大對象

    Beautiful Soup將復雜HTML文檔轉換成一個復雜的樹形結構,每個節點都是Python對象,所有對象可以歸納為4種:

  • Tag
  • NavigableString
  • BeautifulSoup
  • Comment

(1)Tag

    Tag通俗點講就是HTML中的一個個標簽,例如

<title>Jack_Cui</title>
  • 1

    上面的title就是HTML標簽,標簽加入里面包括的內容就是Tag,下面我們來感受一下怎樣用 Beautiful Soup 來方便地獲取 Tags。

    下面每一段代碼中注釋部分即為運行結果:

print(soup.title)
#<title>Jack_Cui</title> print(soup.head) #<head> <title>Jack_Cui</title></head> print(soup.a) #<a class="sister" href="http://blog.csdn.net/c406495762/article/details/58716886" id="link1">Python3網絡爬蟲(一):利用urllib進行簡單的網頁抓取</a> print(soup.p) #<p class="title" name="blog"><b>My Blog</b></p>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

    我們可以利用 soup加標簽名輕松地獲取這些標簽的內容,是不是感覺比正則表達式方便多了?不過有一點是,它查找的是在所有內容中的第一個符合要求的標簽,如果要查詢所有的標簽,我們在后面進行介紹。

    我們也可驗證一下這些對象的類型:

print(type(soup.title)) #<class 'bs4.element.Tag'>
  • 1
  • 2

    對於Tag,有兩個重要的屬性:name和attrs

name:

print(soup.name) print(soup.title.name) #[document] #title
  • 1
  • 2
  • 3
  • 4

    soup 對象本身比較特殊,它的 name 即為 [document],對於其他內部標簽,輸出的值便為標簽本身的名稱。

attrs:

print(soup.a.attrs)
#{'class': ['sister'], 'href': 'http://blog.csdn.net/c406495762/article/details/58716886', 'id': 'link1'}
  • 1
  • 2

    在這里,我們把 a 標簽的所有屬性打印輸出了出來,得到的類型是一個字典。

    如果我們想要單獨獲取某個屬性,可以這樣,例如我們獲取a標簽的class叫什么,兩個等價的方法如下:

print(soup.a['class']) print(soup.a.get('class')) #['sister'] #['sister']
  • 1
  • 2
  • 3
  • 4

(2)NavigableString

    既然我們已經得到了標簽的內容,那么問題來了,我們要想獲取標簽內部的文字怎么辦呢?很簡單,用 .string 即可,例如

print(soup.title.string) #Jack_Cui
  • 1
  • 2

(3)BeautifulSoup

    BeautifulSoup 對象表示的是一個文檔的全部內容.大部分時候,可以把它當作 Tag 對象,是一個特殊的 Tag,我們可以分別獲取它的類型,名稱,以及屬性:

print(type(soup.name)) print(soup.name) print(soup.attrs) #<class 'str'> #[document] #{}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

(4)Comment

    Comment對象是一個特殊類型的NavigableString對象,其實輸出的內容仍然不包括注釋符號,但是如果不好好處理它,可能會對我們的文本處理造成意想不到的麻煩。

print(soup.li)
print(soup.li.string)
print(type(soup.li.string))
#<li><!--注釋--></li> #注釋 #<class 'bs4.element.Comment'>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

    li標簽里的內容實際上是注釋,但是如果我們利用 .string 來輸出它的內容,我們發現它已經把注釋符號去掉了,所以這可能會給我們帶來不必要的麻煩。

    我們打印輸出下它的類型,發現它是一個 Comment 類型,所以,我們在使用前最好做一下判斷,判斷代碼如下:

from bs4 import element if type(soup.li.string) == element.Comment: print(soup.li.string)
  • 1
  • 2
  • 3
  • 4

    上面的代碼中,我們首先判斷了它的類型,是否為 Comment 類型,然后再進行其他操作,如打印輸出。

c)遍歷文檔數

(1)直接子節點(不包含孫節點)

contents:

    tag的content屬性可以將tag的子節點以列表的方式輸出:

print(soup.body.contents)

#['\n', <p class="title" name="blog"><b>My Blog</b></p>, '\n', <li><!--注釋--></li>, '\n', <a class="sister" href="http://blog.csdn.net/c406495762/article/details/58716886" id="link1">Python3網絡爬蟲(一):利用urllib進行簡單的網頁抓取</a>, <br/>, '\n', <a class="sister" href="http://blog.csdn.net/c406495762/article/details/59095864" id="link2">Python3網絡爬蟲(二):利#用urllib.urlopen發送數據</a>, <br/>, '\n', <a class="sister" href="http://blog.csdn.net/c406495762/article/details/59488464" id="link3">Python3網絡爬蟲(三):urllib.error異常</a>, <br/>, '\n']
  • 1
  • 2
  • 3

    輸出方式為列表,我們可以用列表索引來獲取它的某一個元素:

print(soup.body.contents[1])
<p class="title" name="blog"><b>My Blog</b></p>
  • 1
  • 2

children:

    它返回的不是一個 list,不過我們可以通過遍歷獲取所有子節點,它是一個 list 生成器對象:

for child in soup.body.children: print(child)
  • 1
  • 2

    結果如下圖所示:

 

 

 

 

(2)搜索文檔樹

find_all(name, attrs, recursive, text, limit, **kwargs):

    find_all() 方法搜索當前tag的所有tag子節點,並判斷是否符合過濾器的條件。

1) name參數:

    name 參數可以查找所有名字為 name 的tag,字符串對象會被自動忽略掉。

傳遞字符:

    最簡單的過濾器是字符串,在搜索方法中傳入一個字符串參數,Beautiful Soup會查找與字符串完整匹配的內容,下面的例子用於查找文檔中所有的<a>標簽:

print(soup.find_all('a'))

#['\n', <p class="title" name="blog"><b>My Blog</b></p>, '\n', <li><!--注釋--></li>, '\n', <a class="sister" href="http://blog.csdn.net/c406495762/article/details/58716886" id="link1">Python3網絡爬蟲(一):利用urllib進行簡單的網頁抓取</a>, <br/>, '\n', <a class="sister" href="http://blog.csdn.net/c406495762/article/details/59095864" id="link2">Python3網絡爬蟲(二):利用urllib.urlopen發送數據</a>, <br/>, '\n', <a class="sister" href="http://blog.csdn.net/c406495762/article/details/59488464" id="link3">Python3網絡爬蟲(三):urllib.error異常</a>, <br/>, '\n']
  • 1
  • 2
  • 3

傳遞正則表達式:

    如果傳入正則表達式作為參數,Beautiful Soup會通過正則表達式的 match() 來匹配內容.下面例子中找出所有以b開頭的標簽,這表示<body><b>標簽都應該被找到

import re
for tag in soup.find_all(re.compile("^b")): print(tag.name) #body #b #br #br #br
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

傳遞列表:

    如果傳入列表參數,Beautiful Soup會將與列表中任一元素匹配的內容返回,下面代碼找到文檔中所有<title>標簽和<b>標簽:

print(soup.find_all(['title','b'])) #[<title>Jack_Cui</title>, <b>My Blog</b>]
  • 1
  • 2

傳遞True:

    True 可以匹配任何值,下面代碼查找到所有的tag,但是不會返回字符串節點:

for tag in soup.find_all(True): print(tag.name)
  • 1
  • 2

    運行結果:

 

 

 

 

2)attrs參數

    我們可以通過 find_all() 方法的 attrs 參數定義一個字典參數來搜索包含特殊屬性的tag。

print(soup.find_all(attrs={"class":"title"}))
#[<p class="title" name="blog"><b>My Blog</b></p>]
  • 1
  • 2

3)recursive參數

    調用tag的 find_all() 方法時,Beautiful Soup會檢索當前tag的所有子孫節點,如果只想搜索tag的直接子節點,可以使用參數 recursive=False。

4)text參數

    通過 text 參數可以搜搜文檔中的字符串內容,與 name 參數的可選值一樣, text 參數接受字符串 , 正則表達式 , 列表, True。

print(soup.find_all(text="Python3網絡爬蟲(三):urllib.error異常")) #['Python3網絡爬蟲(三):urllib.error異常']
  • 1
  • 2

5)limit參數

    find_all() 方法返回全部的搜索結構,如果文檔樹很大那么搜索會很慢.如果我們不需要全部結果,可以使用 limit 參數限制返回結果的數量.效果與SQL中的limit關鍵字類似,當搜索到的結果數量達到 limit 的限制時,就停止搜索返回結果。

    文檔樹中有3個tag符合搜索條件,但結果只返回了2個,因為我們限制了返回數量:

print(soup.find_all("a", limit=2)) #[<a class="sister" href="http://blog.csdn.net/c406495762/article/details/58716886" id="link1">Python3網絡爬蟲(一):利用urllib進行簡單的網頁抓取</a>, <a class="sister" href="http://blog.csdn.net/c406495762/article/details/59095864" id="link2">Python3網絡爬蟲(二):利用urllib.urlopen發送數據</a>]
  • 1
  • 2
  • 3

6)kwargs參數

    如果傳入 class 參數,Beautiful Soup 會搜索每個 class 屬性為 title 的 tag 。kwargs 接收字符串,正則表達式

print(soup.find_all(class_="title"))
#[<p class="title" name="blog"><b>My Blog</b></p>]
  • 1
  • 2

4.小說內容爬取

    掌握以上內容就可以進行本次實戰練習了

a)單章小說內容爬取

    打開《一念永恆》小說的第一章,進行審查元素分析。

    URL:http://www.biqukan.com/1_1094/5403177.html

    由審查結果可知,文章的內容存放在id為content,class為showtxt的div標簽中:

 

 

 

 

    局部放大:

 

 

 

 

    因此我們,可以使用如下方法將本章小說內容爬取下來:

# -*- coding:UTF-8 -*- from urllib import request from bs4 import BeautifulSoup if __name__ == "__main__": download_url = 'http://www.biqukan.com/1_1094/5403177.html' head = {} head['User-Agent'] = 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19' download_req = request.Request(url = download_url, headers = head) download_response = request.urlopen(download_req) download_html = download_response.read().decode('gbk','ignore') soup_texts = BeautifulSoup(download_html, 'lxml') texts = soup_texts.find_all(id = 'content', class_ = 'showtxt') soup_text = BeautifulSoup(str(texts), 'lxml') #將\xa0無法解碼的字符刪除 print(soup_text.div.text.replace('\xa0',''))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

    運行結果:

 

 

 

 

    可以看到,我們已經順利爬取第一章內容,接下來就是如何爬取所有章的內容,爬取之前需要知道每個章節的地址。因此,我們需要審查《一念永恆》小說目錄頁的內容。

b)各章小說鏈接爬取

    URL:http://www.biqukan.com/1_1094/

    由審查結果可知,小說每章的鏈接放在了class為listmain的div標簽中。鏈接具體位置放在html->body->div->dd->dl->a的href屬性中,例如下圖的第759章的href屬性為/1_1094/14235101.html,那么該章節的地址為:http://www.biqukan.com/1_1094/14235101.html

 

 

 

 

    局部放大:

 

 

 

 

    因此,我們可以使用如下方法獲取正文所有章節的地址:

# -*- coding:UTF-8 -*- from urllib import request from bs4 import BeautifulSoup if __name__ == "__main__": target_url = 'http://www.biqukan.com/1_1094/' head = {} head['User-Agent'] = 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19' target_req = request.Request(url = target_url, headers = head) target_response = request.urlopen(target_req) target_html = target_response.read().decode('gbk','ignore') #創建BeautifulSoup對象 listmain_soup = BeautifulSoup(target_html,'lxml') #搜索文檔樹,找出div標簽中class為listmain的所有子標簽 chapters = listmain_soup.find_all('div',class_ = 'listmain') #使用查詢結果再創建一個BeautifulSoup對象,對其繼續進行解析 download_soup = BeautifulSoup(str(chapters), 'lxml') #開始記錄內容標志位,只要正文卷下面的鏈接,最新章節列表鏈接剔除 begin_flag = False #遍歷dl標簽下所有子節點 for child in download_soup.dl.children: #濾除回車 if child != '\n': #找到《一念永恆》正文卷,使能標志位 if child.string == u"《一念永恆》正文卷": begin_flag = True #爬取鏈接 if begin_flag == True and child.a != None: download_url = "http://www.biqukan.com" + child.a.get('href') download_name = child.string print(download_name + " : " + download_url)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

    運行結果:

 

 

 

 

c)爬取所有章節內容,並保存到文件中

    整合以上代碼,並進行相應處理,編寫如下代碼:

# -*- coding:UTF-8 -*- from urllib import request from bs4 import BeautifulSoup import re import sys if __name__ == "__main__": #創建txt文件 file = open('一念永恆.txt', 'w', encoding='utf-8') #一念永恆小說目錄地址 target_url = 'http://www.biqukan.com/1_1094/' #User-Agent head = {} head['User-Agent'] = 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19' target_req = request.Request(url = target_url, headers = head) target_response = request.urlopen(target_req) target_html = target_response.read().decode('gbk','ignore') #創建BeautifulSoup對象 listmain_soup = BeautifulSoup(target_html,'lxml') #搜索文檔樹,找出div標簽中class為listmain的所有子標簽 chapters = listmain_soup.find_all('div',class_ = 'listmain') #使用查詢結果再創建一個BeautifulSoup對象,對其繼續進行解析 download_soup = BeautifulSoup(str(chapters), 'lxml') #計算章節個數 numbers = (len(download_soup.dl.contents) - 1) / 2 - 8 index = 1 #開始記錄內容標志位,只要正文卷下面的鏈接,最新章節列表鏈接剔除 begin_flag = False #遍歷dl標簽下所有子節點 for child in download_soup.dl.children: #濾除回車 if child != '\n': #找到《一念永恆》正文卷,使能標志位 if child.string == u"《一念永恆》正文卷": begin_flag = True #爬取鏈接並下載鏈接內容 if begin_flag == True and child.a != None: download_url = "http://www.biqukan.com" + child.a.get('href') download_req = request.Request(url = download_url, headers = head) download_response = request.urlopen(download_req) download_html = download_response.read().decode('gbk','ignore') download_name = child.string soup_texts = BeautifulSoup(download_html, 'lxml') texts = soup_texts.find_all(id = 'content', class_ = 'showtxt') soup_text = BeautifulSoup(str(texts), 'lxml') write_flag = True file.write(download_name + '\n\n') #將爬取內容寫入文件 for each in soup_text.div.text.replace('\xa0',''): if each == 'h': write_flag = False if write_flag == True and each != ' ': file.write(each) if write_flag == True and each == '\r': file.write('\n') file.write('\n\n') #打印爬取進度 sys.stdout.write("已下載:%.3f%%" % float(index/numbers) + '\r') sys.stdout.flush() index += 1 file.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61

    代碼略顯粗糙,運行效率不高,還有很多可以改進的地方,運行效果如下圖所示:

 

 

 

 

    最終生成的txt文件,如下圖所示:

 

 

 

 

    生成的txt文件,可以直接拷貝到手機中進行閱讀,手機閱讀軟件可以解析這樣排版的txt文件。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM