5.3黑客成長日記——爬蟲篇(1)

寫一個小說網(wǎng)站的爬蟲—Test

reference

Python3 網(wǎng)絡(luò)爬蟲(二)
[新筆趣閣](https://www.xsbiquge.com/
beautiful

爬蟲三個步驟:
發(fā)起請求:我們需要先明確如何發(fā)起 HTTP 請求,獲取到數(shù)據(jù)。
解析數(shù)據(jù):獲取到的數(shù)據(jù)亂七八糟的,我們需要提取出我們想要的數(shù)據(jù)。
保存數(shù)據(jù):將我們想要的數(shù)據(jù),保存。

首先是工具

beautifulSoup HTML解析工具

簡介

Beautiful Soup將復(fù)雜HTML文檔轉(zhuǎn)換成一個復(fù)雜的樹形結(jié)構(gòu),每個節(jié)點都是Python對象,所有對象可以歸納為4種:
-Tag #標(biāo)簽
-NavigableString #內(nèi)容
-BeautifulSoup #document對象
-Comment #注釋
后面內(nèi)容請對照代碼來觀看

import re
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  class="sister" id="link1">
Python3網(wǎng)絡(luò)爬蟲(一):利用urllib進(jìn)行簡單的網(wǎng)頁抓取</a><br/>
<a  class="sister" id="link2">
Python3網(wǎng)絡(luò)爬蟲(二):利用urllib.urlopen發(fā)送數(shù)據(jù)</a><br/>
<a  class="sister" id="link3">
Python3網(wǎng)絡(luò)爬蟲(三):urllib.error異常</a><br/>
</body>
</html>
"""

#創(chuàng)建Beautiful Soup對象
# soup = BeautifulSoup(html)
soup = BeautifulSoup(html, "html.parser")
#soup = BeautifulSoup(open('index.html'))

print(soup.prettify())
print(soup.name)
print(soup.a.string)
print(soup.a.contents)
print(soup.br.contents)
print(soup.li.contents)
print(soup.head.contents)

for i,child in  enumerate(soup.body.children):
    print("child", i, ":",child)

print("\n"*10)
print("______________")
c = soup.find_all("a")
c = soup.find_all(["a", 'b'])
# c = soup.find_all([re.compile('^b')])
print(c)
for i in c:
    print(i.get_text())

print("\n"*10)
print("______________")
print(soup.select('#link1'))
print(soup.select("head > title"))
print(soup.select("body > a")[0].get_text())

Beautiful Soup 最后會把所有的節(jié)點變成樹的一個屬性。

三種解析器

三種解析器.png

未來方便查詢,同時提供了findall函數(shù)來查找:

find_all

1.name 參數(shù)
name 參數(shù)可以查找所有名字為 name 的tag
A.傳[標(biāo)簽的]字符串
B.傳[標(biāo)簽的]正則表達(dá)式
C.傳[標(biāo)簽的]列表
2.text 參數(shù)
直接上文本,當(dāng)然把上面標(biāo)簽的換成文本的,都適用,強大的解析器。
3.keyword 參數(shù)
傳id 的
4.class參數(shù)
attrs={"class":"footer"}

get_text()

當(dāng)然獲得的結(jié)果會有一些標(biāo)簽名字在里面,方便debug,所以真正獲得其內(nèi)容,再來一個get_text()函數(shù)
對應(yīng)到屬性里面獲取內(nèi)容的.string

Css選擇器

有眾多和find_all交叉的功能,但是咱也用不上
突出說幾個
1.組合查找
查找 p 標(biāo)簽中,id 等于 link1的內(nèi)容,二者需要用空格分開
查找body標(biāo)簽下的a標(biāo)簽內(nèi)容,則使用 > 分隔
~ 表示所有其他兄弟標(biāo)簽;屬
+ 表示第一個其他兄弟標(biāo)簽。

進(jìn)入正題

代碼也沒上面難點,主要是三個部分
正文解析,在原作者里沒有用get_text()這個寶貝方法,可以去掉string里面所有的標(biāo)簽。

    target = 'https://www.xsbiquge.com/15_15338/8549128.html'
    html_context = crawer(target, i, online=False)
    # soup = BeautifulSoup(html_context, features="lxml")
    soup = BeautifulSoup(html_context, features="lxml")
    # print(soup.prettify())
    # print("\n"*10)
    # 文章標(biāo)題
    title = soup.head.title.string[:-7]
    print("Mining\t\t\t", soup.title.string)
    # 文章內(nèi)容
    # res = soup.select("#content")
    res = soup.find_all('div', id='content')
    if res:
        content = res[0].get_text()
        content_format = '\n    '.join(content.split('    '))

next_link 處理,找到next link的方法也千奇百怪,原作者是通過目錄頁來找的。
也可以像我一樣在link里面找,或者是構(gòu)造link(注釋中)

nl_tmp = soup.find_all('a', text="下一章")
if nl_tmp:
    nl = nl_tmp[0].get('href')
    print(nl)
    return "https://www.xsbiquge.com" + nl
    # # constract way
    # target_head = target[:-13]
    # target_page = int(target[-12:-5])
    # # print(target_head, target_page)
    # page = str(target_page + 1)
    # return target_head + '/' + page + '.html'

中間未來debug,在crawler中加了一個online的選項。主要是不想給對方的服務(wù)器太大的壓力。

def crawer(target, i, online=True):
    if online:
        req = requests.get(url = target)
        req.encoding = 'utf-8'
        # print(req.text)
        with open('spider/raw/'+str(i)+'_'+target.split('/')[-1], 'w', encoding='utf-8') as file:
            file.write(req.text)
        return req.text
    else:
        with open('spider/raw/'+str(i)+'_'+target.split('/')[-1], 'r', encoding='utf-8') as file:
            # for line in file.realines():
            html_context = file.read()
        return html_context

全代碼

import requests
from bs4 import BeautifulSoup

def next_link(target):
    # read link way
    nl_tmp = soup.find_all('a', text="下一章")
    if nl_tmp:
        nl = nl_tmp[0].get('href')
        print(nl)
        return "https://www.xsbiquge.com" + nl
    # # constract way
    # target_head = target[:-13]
    # target_page = int(target[-12:-5])
    # # print(target_head, target_page)
    # page = str(target_page + 1)
    # return target_head + '/' + page + '.html'


def crawer(target, i, online=True):
    if online:
        req = requests.get(url = target)
        req.encoding = 'utf-8'
        # print(req.text)
        with open('spider/raw/'+str(i)+'_'+target.split('/')[-1], 'w', encoding='utf-8') as file:
            file.write(req.text)
        return req.text
    else:
        with open('spider/raw/'+str(i)+'_'+target.split('/')[-1], 'r', encoding='utf-8') as file:
            # for line in file.realines():
            html_context = file.read()
        return html_context

def save_by_chapter(title, content_format):
    with open("spider/cooked/"+title+'.txt', 'w', encoding='utf-8') as file:
        file.write('\n\n'+" "*10+title+'\n\n')
        file.write(content_format)


def save_by_book(title, content_format):
    with open("spider/cooked/詭秘之主_全本.txt", 'a+', encoding='utf-8') as file:
        file.write('\n\n'+" "*10+title+'\n\n')
        file.write(content_format)


if __name__ == '__main__':
    target = 'https://www.xsbiquge.com/15_15338/8549128.html'
    # target = "https://www.xsbiquge.com/15_15338/8549135.html"
    number_of_chapter = 20
    for i in range(number_of_chapter):
        print(target)
        html_context = crawer(target, i, online=True)
        # soup = BeautifulSoup(html_context, features="lxml")
        soup = BeautifulSoup(html_context, features="lxml")
        # print(soup.prettify())
        # print("\n"*10)
        # 文章標(biāo)題
        title = soup.head.title.string[:-7]
        print("Mining\t\t\t", soup.title.string)
        # 文章內(nèi)容
        # res = soup.select("#content")
        res = soup.find_all('div', id='content')
        if res:
            content = res[0].get_text()
            content_format = '\n    '.join(content.split('    '))
            save_by_chapter(title, content_format)
            save_by_book(title, content_format)
            print(title,"\t\t\tsave successfully")
        else:
            print("False Page\t\t\t", target)
        #下一章
        nl = soup.find_all('div', attrs={"class":"bottem1"})
        target = next_link(target)

尾聲

還可以tqdm顯示進(jìn)度條,等等。
對了,不推薦下載盜版小說。

20 多分鐘下載一本小說,你可能感覺太慢了。想提速,可以使用多進(jìn)程,大幅提高下載速度。如果使用分布式,甚至可以1秒鐘內(nèi)下載完畢。
但是,我不建議這樣做。
我們要做一個友好的爬蟲,如果我們?nèi)ヌ崴?,那么我們訪問的服務(wù)器也會面臨更大的壓力。
以我們這次下載小說的代碼為例,每秒鐘下載 1 個章節(jié),服務(wù)器承受的壓力大約 1qps,意思就是,一秒鐘請求一次。
如果我們 1 秒同時下載 1416 個章節(jié),那么服務(wù)器將承受大約 1416 qps 的壓力,這還是僅僅你發(fā)出的并發(fā)請求數(shù),再算上其他的用戶的請求,并發(fā)量可能更多。
如果服務(wù)器資源不足,這個并發(fā)量足以一瞬間將服務(wù)器“打死”,特別是一些小網(wǎng)站,都很脆弱。
過大并發(fā)量的爬蟲程序,相當(dāng)于發(fā)起了一次 CC 攻擊,并不是所有網(wǎng)站都能承受百萬級別并發(fā)量的。
所以,寫爬蟲,一定要謹(jǐn)慎,勿給服務(wù)器增加過多的壓力,滿足我們的獲取數(shù)據(jù)的需求,這就夠了。
你好,我也好,大家好才是真的好。

使用一:幫師父爬取小說
至尊龍帝陸鳴
和上面的主要區(qū)別是gbk
全代碼

#!/usr/bin/python

import requests
from bs4 import BeautifulSoup

def next_link(soup):
    # read link way
    nl_tmp = soup.find_all('a', text="下一章")
    if nl_tmp:
        nl = nl_tmp[0].get('href')
        print(nl)
        return "https://www.rzlib.net" + nl
    # # constract way
    # target_head = target[:-13]
    # target_page = int(target[-12:-5])
    # # print(target_head, target_page)
    # page = str(target_page + 1)
    # return target_head + '/' + page + '.html'


def crawer(target, i, online=True):
    if online:
        req = requests.get(url = target, headers={'User-Agent': 'Chrome'})
        req.encoding = 'GBK'
        # print(req.text)
        with open('spider/raw/'+str(i)+'_'+target.split('/')[-1], 'w') as file:
            file.write(req.text)
        return req.text
    else:
        with open('spider/raw/'+str(i)+'_'+target.split('/')[-1], 'r') as file:
            # for line in file.realines():
            html_context = file.read()
        return html_context


def save_by_chapter(title, content_format):
    with open("spider/cooked/"+title+'.txt', 'w', encoding='utf-8') as file:
        file.write('\n\n'+" "*10+title+'\n\n')
        file.write(content_format)


def save_by_book(title, content_format):
    with open("spider/cooked/至尊龍帝陸鳴1360plus.txt", 'a+', encoding='utf-8') as file:
        file.write('\n\n'+" "*10+title+'\n\n')
        file.write(content_format)

rpstr = []

if __name__ == '__main__':
    target = 'https://www.rzlib.net/b/73/73820/32494178.html'
    number_of_chapter = 3200
    for i in range(number_of_chapter):
        print(target)
        html_context = crawer(target, i, online=True)
        # soup = BeautifulSoup(html_context, features="lxml")
        soup = BeautifulSoup(html_context, "html5lib")
        # print(soup.prettify())
        # print("\n"*10)
        # 文章標(biāo)題
        title = soup.head.title.string[:-7]
        print("Mining\t\t\t", soup.title.string)
        # 文章內(nèi)容
        # res = soup.select("#content")
        res = soup.find_all('div', id='chapter_content')
        if res:
            content_format = content = res[0].get_text()
            for a, b in rpstr:
                content_format = content_format.replace(a,b)
            # save_by_chapter(title, content_format)
            save_by_book(title, content_format)
            print(title,"\t\t\tsave successfully")
        else:
            print("False Page\t\t\t", target)
        #下一章
        nl = soup.find_all('div', attrs={"class":"bottem1"})
        target = next_link(soup)

中途遇到了error,max retry啥的,沒解決。重跑了兩次,第三次就好了。

Connection aborted.', RemoteDisconnected('Remote end closed connection without response
添加
headers = {'User-Agent': 'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容