轉載請註明作者和出處:http://blog.csdn.net/c406495762
運行平臺: Windows
Python版本: Python3.x
IDE: Sublime text3
一、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
b)easy_install安裝
easy_install beautifulsoup4
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
- 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')
使用如下代碼格式化輸出:
print(soup.prettify())
b)Beautiful Soup四大對象
Beautiful Soup將複雜HTML文檔轉換成一個複雜的樹形結構,每個節點都是Python對象,所有對象可以歸納爲4種:
- Tag
- NavigableString
- BeautifulSoup
- Comment
(1)Tag
Tag通俗點講就是HTML中的一個個標籤,例如
<title>Jack_Cui</title>
上面的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>
我們可以利用 soup加標籤名輕鬆地獲取這些標籤的內容,是不是感覺比正則表達式方便多了?不過有一點是,它查找的是在所有內容中的第一個符合要求的標籤,如果要查詢所有的標籤,我們在後面進行介紹。
我們也可驗證一下這些對象的類型:
print(type(soup.title))
#<class 'bs4.element.Tag'>
對於Tag,有兩個重要的屬性:name和attrs
name:
print(soup.name)
print(soup.title.name)
#[document]
#title
soup 對象本身比較特殊,它的 name 即爲 [document],對於其他內部標籤,輸出的值便爲標籤本身的名稱。
attrs:
print(soup.a.attrs)
#{'class': ['sister'], 'href': 'http://blog.csdn.net/c406495762/article/details/58716886', 'id': 'link1'}
在這裏,我們把 a 標籤的所有屬性打印輸出了出來,得到的類型是一個字典。
如果我們想要單獨獲取某個屬性,可以這樣,例如我們獲取a標籤的class叫什麼,兩個等價的方法如下:
print(soup.a['class'])
print(soup.a.get('class'))
#['sister']
#['sister']
(2)NavigableString
既然我們已經得到了標籤的內容,那麼問題來了,我們要想獲取標籤內部的文字怎麼辦呢?很簡單,用 .string 即可,例如
print(soup.title.string)
#Jack_Cui
(3)BeautifulSoup
BeautifulSoup 對象表示的是一個文檔的全部內容.大部分時候,可以把它當作 Tag 對象,是一個特殊的 Tag,我們可以分別獲取它的類型,名稱,以及屬性:
print(type(soup.name))
print(soup.name)
print(soup.attrs)
(4)Comment
Comment對象是一個特殊類型的NavigableString對象,其實輸出的內容仍然不包括註釋符號,但是如果不好好處理它,可能會對我們的文本處理造成意想不到的麻煩。
print(soup.li)
print(soup.li.string)
print(type(soup.li.string))
#<li></li>
#註釋
#<class 'bs4.element.Comment'>
li標籤裏的內容實際上是註釋,但是如果我們利用 .string 來輸出它的內容,我們發現它已經把註釋符號去掉了,所以這可能會給我們帶來不必要的麻煩。
我們打印輸出下它的類型,發現它是一個 Comment 類型,所以,我們在使用前最好做一下判斷,判斷代碼如下:
from bs4 import element
if type(soup.li.string) == element.Comment:
print(soup.li.string)
上面的代碼中,我們首先判斷了它的類型,是否爲 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']
輸出方式爲列表,我們可以用列表索引來獲取它的某一個元素:
print(soup.body.contents[1])
<p class="title" name="blog"><b>My Blog</b></p>
children:
它返回的不是一個 list,不過我們可以通過遍歷獲取所有子節點,它是一個 list 生成器對象:
for child in soup.body.children:
print(child)
結果如下圖所示:
(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']
傳遞正則表達式:
如果傳入正則表達式作爲參數,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
傳遞列表:
如果傳入列表參數,Beautiful Soup會將與列表中任一元素匹配的內容返回,下面代碼找到文檔中所有<title>
標籤和<b>
標籤:
print(soup.find_all(['title','b']))
#[<title>Jack_Cui</title>, <b>My Blog</b>]
傳遞True:
True 可以匹配任何值,下面代碼查找到所有的tag,但是不會返回字符串節點:
for tag in soup.find_all(True):
print(tag.name)
運行結果:
2)attrs參數
我們可以通過 find_all() 方法的 attrs 參數定義一個字典參數來搜索包含特殊屬性的tag。
print(soup.find_all(attrs={"class":"title"}))
#[<p class="title" name="blog"><b>My Blog</b></p>]
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異常']
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>]
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>]
4.小說內容爬取
掌握以上內容就可以進行本次實戰練習了
a)單章小說內容爬取
打開《一念永恆》小說的第一章,進行審查元素分析。
URL:http://www.biqukan.com/1_1094/5403177.html
由審查結果可知,文章的內容存放在id爲content,class爲showtxt的div標籤中:
局部放大:
因此我們,可以使用如下方法將本章小說內容爬取下來:
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')
print(soup_text.div.text.replace('\xa0',''))
運行結果:
可以看到,我們已經順利爬取第一章內容,接下來就是如何爬取所有章的內容,爬取之前需要知道每個章節的地址。因此,我們需要審查《一念永恆》小說目錄頁的內容。
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
局部放大:
因此,我們可以使用如下方法獲取正文所有章節的地址:
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')
listmain_soup = BeautifulSoup(target_html,'lxml')
chapters = listmain_soup.find_all('div',class_ = 'listmain')
download_soup = BeautifulSoup(str(chapters), 'lxml')
begin_flag = False
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
- 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)爬取所有章節內容,並保存到文件中
整合以上代碼,並進行相應處理,編寫如下代碼:
from urllib import request
from bs4 import BeautifulSoup
import re
import sys
if __name__ == "__main__":
file = open('一念永恆.txt', 'w', encoding='utf-8')
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')
listmain_soup = BeautifulSoup(target_html,'lxml')
chapters = listmain_soup.find_all('div',class_ = 'listmain')
download_soup = BeautifulSoup(str(chapters), 'lxml')
numbers = (len(download_soup.dl.contents) - 1) / 2 - 8
index = 1
begin_flag = False
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
- 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文件。
PS:如果覺得本篇本章對您有所幫助,歡迎關注、評論、點贊,謝謝!
參考文章:
URL:http://cuiqingcai.com/1319.html
2017年5月6日更新:
對代碼進行了更改:添加了對錯誤章節的處理,並剔除了不是正文的部分。支持《筆趣看》網站大部分的小說下載。
代碼查看:
Github代碼連接:點擊打開鏈接