1. 程式人生 > >Python爬蟲從入門到精通(3): BeautifulSoup用法總結及多執行緒爬蟲爬取糗事百科

Python爬蟲從入門到精通(3): BeautifulSoup用法總結及多執行緒爬蟲爬取糗事百科

本文是Python爬蟲從入門到精通系列的第3篇。我們將總結BeautifulSoup這個解析庫以及常用的find和select方法。我們還會利用requests庫和BeauitfulSoup來爬取糗事百科上的段子, 並對比下單執行緒爬蟲和多執行緒爬蟲的爬取效率。

什麼是BeautifulSoup及如何安裝

BeautifulSoup是一個解析HTML或XML檔案的第三方庫。HTML或XML檔案可以用DOM模型解釋,一般包含三種節點:

  • 元素節點 - 通常指HTML或XML的標籤(tag), 如title, p, a

  • 文字節點 - 標籤內部的文字內容(string 或者text)

  • 屬性節點 - 每個標籤的屬性(attribute)。

BeautifulSoup庫可以對HTML或XML檔案解析,查詢到一個或多個標籤元素(tag),並獲取每個標籤裡的文字和屬性,這為我們python爬蟲從html文本里提取所需要的內容提供了很大的便利。一個BeautifulSoup很好的特性是它接受一個str或byte物件後會對編碼自動檢測,並把當前文件編碼並轉換成Unicode編碼,這樣你就不用擔心亂碼問題了。

安裝和使用只需要使用如下兩個命令:

pip install beautifulsoup4

from bs4 import BeautifulSoup

我們還建議你安裝lxml HTML解析庫,比python自帶的解析庫html.parser更快。

pip install lxml

安裝好BeautifulSoup物件後,你就可以建立soup物件,並開始後面的查找了。

soup = BeautifulSoup(html, "html.parser")
soup = BeautifulSoup(html, "lxml")

BeautifulSoup庫的使用方法

BeautifulSoup對一個元素的查詢主要有3中方法:

  • 根據標籤名直接查詢 - 比如soup.title, soup.p,僅適用於查詢單個元素

  • 使用find和find_all方法 - 根據標籤名和屬性對文件遍歷查詢提取一個或多個元素。

  • 使用select方法 - 根據css樣式選擇器對文件進行遍歷提取一個或多個元素

# 根據tag直接獲取元素
soup.p #獲取p標籤元素物件,只獲取第一個
soup.p.name #獲取p標籤的名字,即'p"
soup.p.string # 獲取p標籤元素內的文字
soup.p['class'] #獲取p標籤元素的class屬性
soup.p.get('class') #等同於上述案例
soup.a['href'] #獲取第一個a元素的href屬性


# find_all方法。find方法類似,僅用於提取首個匹配元素
# find_all( name , attrs , recursive , text , **kwargs )
#  name :要查詢的標籤名(字串、正則、方法、True)
#  attrs: 標籤的屬性
#  recursive: 遞迴
#  text: 查詢文字
# **kwargs :其它 鍵值引數
# 因class是關鍵字,所以要寫成class_="value", 等同於attrs={"class":"value"}
soup.find_all('p')  # 以列表形式返回所有p標籤
soup.find_all('p', attrs={"class":"sister"})  # 以列表形式返回所有class屬性==sister的p標籤
soup.find_all('p', class_="sister")  # 以列表形式返回所有class屬性==sister的p標籤
soup.find_all(id='link2')  # 返回所有id屬性==link2的標籤
soup.find_all(re.compile("^b"))  # 使用正則查詢標籤以b開頭的元素
soup.find_all(href=re.compile("elsie")) # 使用正則, 返回所有href屬性包含elsie的標籤
soup.find_all(id="link1", href=re.compile('elsie'))  # id=link1且href包含elsie的標籤


# select方法 - css選擇器
# 注意select方法提取的元素均是列表形式,獲取文字時注意加index
soup.select('p') # 根據標籤名查詢所有p元素,等於soup.find_all('p')
soup.select('.sister') # 通過css屬性查詢class=sister的標籤
soup.select('#link1') # 通過id查詢所有id=#link1的元素
soup.select('p #link1') # 組合查詢id=#link11的p元素
soup.select("head > title") # 查詢head標籤的子元素title
soup.select('a[class="sister"]') # 查詢所有屬性為sister的a標籤
soup.select('a[href="http://example.com/elsie"]') #查詢href=xxx的a標籤元素
soup.select('p')[0].get_text() # 獲取首個p元素的文字
soup.select('a[href*=".com/el"]')[0].attrs['href'] #獲取xxx.com的href

除了find()和find_all()之外還有一些非常有用的方法可用來搜尋父子和兄弟節點。使用方法和find_all方法類似。find_parent()

find_parents()

find_next_sibling()

find_next_siblings()

find_previous_sibling()

find_previous_siblings()

find_next()find_previous()find_all_next()find_all_previous()

請注意select方法和find方法有如下區別,使用時請注意:

  • find方法返回的是單個元素,find_all方法返回的是一個元素列表,而select方法永遠返回的是元素列表。如果你使用了select方法查詢到了單個元素,別忘了先加列表索引[0],然後才可以呼叫get_text()方法獲取文字。

  • find方法還支援方法引數查詢,比select方法更強大,如下所示:

def has_class_no_id(tag):
    return tag.has_attr("class") and not tag.has_attr("id")
soup.find_all(has_class_no_id)  # 支援方法引數

BeautifulSoup庫的缺點

BeautifulSoup對元素的查詢很人性化,便於閱讀理解,不過缺點是速度較慢。一個更快的對元素進行查詢的方法是XPATH,我們以後再講解。BeautifulSoup對一般的爬蟲專案已經夠用,我們今天就來使用BeauitfulSoup來爬取糗事百科上的段子, 並對比下單執行緒爬蟲和多執行緒爬蟲的爬取效率。

對比單執行緒和多執行緒爬蟲

我們分別寫個單執行緒和多執行緒爬蟲看看爬取糗事百科前10頁的段子都需要多長時間。爬取結果寫入txt檔案。如果程式碼你看不全,請搜尋csdn大江狗,看全文。

# 單執行緒爬蟲

import requests
from bs4 import BeautifulSoup
import time


headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'
}


if __name__ == "__main__":

    start = time.time()
    f = open("qiushi01.txt", "a", encoding='utf-8')

    url_list = []
    for i in range(1, 11):
        url_list.append('https://www.qiushibaike.com/8hr/page/{}/'.format(i))

    for url in url_list:
        response = requests.get(url, headers=headers)
        soup = BeautifulSoup(response.text, "html.parser")
        div_list = soup.select('.article')

        for div in div_list:
            author = div.select('.author')[0].select('h2')[0].get_text()
            content = div.select('.content')[0].get_text()
            f.write(author)
            f.write(content)

    f.close()
    end = time.time()
    print("下載完成. 用時{}秒".format(end-start))

# 多執行緒爬蟲

import requests
from bs4 import BeautifulSoup
import time
import threading
from queue import Queue


headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'
}


class MyThread(threading.Thread):
    def __init__(self, name, queue, file):
        super().__init__()
        self.name = name
        self.queue = queue
        self.file = file

    def run(self):
        print("啟動{}".format(self.name))
        while not self.queue.empty():
            try:
                url = self.queue.get()
                response = requests.get(url, headers=headers)
                self.parse(response.text)
            except:
                pass
        print("結束{}".format(self.name))

    def parse(self, html):
        soup = BeautifulSoup(html, "html.parser")
        div_list = soup.select('.article')

        for div in div_list:
            author = div.select('.author')[0].select('h2')[0].get_text()
            content = div.select('.content')[0].get_text()
            self.file.write(author + content)


if __name__ == "__main__":

    start = time.time()
    f = open("qiushit10.txt", "a", encoding='utf-8')

    queue = Queue()
    for i in range(1, 11):
        queue.put('https://www.qiushibaike.com/8hr/page/{}/'.format(i))

    thread1 = MyThread("執行緒1", queue, f)
    thread2 = MyThread("執行緒2", queue, f)

    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()

    f.close()
    end = time.time()
    print("下載完成. 用時{}秒".format(end-start))

# 爬取結果

# 單執行緒爬蟲
(venv) C:\Users\MissEnka\PycharmProjects\spider>python qiushi.py
下載完成. 用時3.873957872390747秒

# 多執行緒爬蟲
(venv) C:\Users\MissEnka\PycharmProjects\spider>python qiushit.py
啟動執行緒1
啟動執行緒2
結束執行緒2
結束執行緒1
下載完成. 用時2.473332643508911秒

由此可見,多執行緒爬蟲還是節約了大概35%的時間。大家不是說python因為GIL鎖的原因多執行緒程式設計是雞肋嗎? 其實不是。至於為什麼請閱讀一文看懂Python多程序與多執行緒程式設計(工作學習面試必讀)

大江狗

2018.10