Web 抓取:Selenium 與 BeautifulSoup 的對比。


我們可以使用 Selenium Webdriver 和 BeautifulSoup 來執行 web 抓取。Web 抓取用於從頁面中提取內容。在 Python 中,這是透過 BeautifulSoup 包實現的。

我們抓取並獲取頁面上的以下連結 −

我們還將看到上述連結的 html 結構 −

我們來看看如何使用 BeautifulSoup 進行 web 抓取

要安裝 Beautifulsoup 所需的包,我們應該執行以下命令 −

pip install bs4
pip install requests

示例

from bs4 import BeautifulSoup
import requests
#get all response
d=requests.get("https://tutorialspoint.tw/about/about_careers.htm")
#response content whole page in html format
s = BeautifulSoup(d.content, 'html.parser')
#access to specific ul element with BeautifulSoup methods
l = s.find('ul', {'class':'toc reading'})
#access all children of ul
rs = l.findAll('li')
   for r in rs:
      #get text of li elements
         print(r.text)

現在,我們來看看如何將 BeautifulSoup 與 Selenium 一起用於 web 抓取。

要將 BeautifulSoup 與 Selenium 一起使用,我們應該執行命令 −

pip install bs4 selenium

示例

from selenium import webdriver
from bs4 import BeautifulSoup
#path of chromedriver.exe
driver = webdriver.Chrome (executable_path="C:\chromedriver.exe")
#launch browser
driver.get ("https://tutorialspoint.tw/about/about_careers.htm")
#content whole page in html format
s = BeautifulSoup(driver.page_source, 'html.parser')
#access to specific ul element with BeautifulSoup methods
l = s.find('ul', {'class':'toc reading'})
#get all li elements under ul
rs = l.findAll('li')
for r in rs:
   #get text of li elements
      print(r.text)

輸出

更新於: 2021 年 1 月 30 日

258 次瀏覽

開啟你的事業

透過完成課程來獲得認證

開始
廣告