一、BeautifulSoup簡介
BeautifulSoup是Python最受歡迎的HTML/XML解析庫之一,它能將復雜的網頁文檔轉換為樹形結構,支持多種解析器(如lxml、html.parser)。配合requests庫,可以快速構建網頁爬蟲項目。
二、環境準備
pip install requests beautifulsoup4 matplotlib
三、實戰:百度熱搜數據獲取
1. 獲取網頁內容
import requests from bs4 import BeautifulSoupurl = 'https://top.baidu.com/board?tab=realtime' headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' }response = requests.get(url, headers=headers) html = response.content
2. 解析HTML結構
使用Chrome開發者工具(