爬蟲2-BeautifulSoup (Python)

Outsider987
Feb 27, 2021

--

我們來談談BeautifulSoup,有關美麗的湯

快點跟上,來不及了

Beautiful Soup是一個Python庫,用於從HTML和XML文件中提取數據,甚麼你不知道HTML是甚麼,快來看看這篇文章吧 (晚點附上),簡單說他就是一個尋找HTML標籤的涵式庫

Beautiful Soup

來來來~~先附上Import的新鮮程式碼,並且把它寫在最上面喔

import scrapy
from bs4 import BeautifulSoup

我們這樣就可以使用BeautifulSoup啦,話不多說馬上來作範例:(這邊我們採取用金正恩領導人的維基來作範例)

from bs4 import BeautifulSoup
from scrapy.crawler import CrawlerProcess
class ExampleSpider(scrapy.Spider):
name = 'example'
allowed_domains = ['example.com']
start_urls = ['<https://zh.wikipedia.org/wiki/%E9%87%91%E6%AD%A3%E6%81%A9>']
def parse(self, response):
content = response.body
soup = BeautifulSoup(content, "html5lib")
print(soup)
#這邊放在程式碼最底下 好讓你可以在IDE直接執行可以看內容
process = CrawlerProcess()
process.crawl(ExampleSpider)process.start()

利用VS code執行後在我們的終端機應該可以看這樣的內容(或是直接在終端機輸入 scrapy crawl example)

這部分的code是發出request然後把回傳的資料解析,而這些回傳解析是靠BeautifulSoup所print出來的

我們來打開google的devtool吧(也可以再chrome按下F12)

在上面的圖案你可以看到我紅框起來的資料是一樣的,而BeautifulSoup就是幫我們把回傳的資料解析成這樣,這樣你就可以針對Html的某個標籤進行萃取你所需要的資料

BeautifulSoup參數

def parse(self, response):
content = response.body
soup = BeautifulSoup(content, "html5lib")

在使用除了第一個參數通常都是既定的,我們來介紹一下第二個參數,我列了一張表在下面供給大家參考

解析器使用方法優勢劣勢Python標準庫BeautifulSoup(markup, “html.parser”)

  • Python的內置標準庫
  • 執行速度適中
  • 文檔容錯能力強
  • Python 2.7.3 or 3.2.2)前 的版本中文檔容錯能力差

lxml HTML 解析器BeautifulSoup(markup, “lxml”)

  • 速度快
  • 文檔容錯能力強
  • 需要安裝C語言庫

lxml XML 解析器BeautifulSoup(markup, [“lxml”, “xml”])BeautifulSoup(markup, “xml”)

  • 速度快
  • 唯一支持XML的解析器
  • 需要安裝C語言庫

html5libBeautifulSoup(markup, “html5lib”)

  • 最好的容錯性
  • 以瀏覽器的方式解析文檔
  • 生成HTML5格式的文檔
  • 速度慢

下一篇文我們來講講如何確切使用BeautifulSoup吧

說了這麼多,看完文章你做了甚麼?

還不給我訂起來~~~(ʘ言ʘ╬)

--

--

Outsider987
Outsider987

Written by Outsider987

Hi, this is Victor In my college I was majors medical chemistry ,but I found the programing is interesting stuff I never met ,so I start to learning computer s

No responses yet