如何在Python中使用Selenium和Beautifulsoup解析網站?


我們可以在Python中使用Selenium和Beautiful Soup解析網站。Web爬取是一個從網頁中提取內容的概念,廣泛用於資料科學和指標準備。在Python中,它透過BeautifulSoup軟體包實現。

要獲得BeautifulSoup和Selenium,我們應該執行命令−

pip install bs4 selenium

讓我們抓取頁面上出現的以下連結 −

然後調查上述元素的html結構 −

示例

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 chapters'})
#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日

2K+ 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始
廣告