BeautifulSoup 是一個 Python 庫,用于解析 HTML 和 XML 文檔。它本身不具備爬蟲功能,但可以與其他庫(如 Requests)結合使用來實現爬蟲功能。BeautifulSoup 可以用來更新網頁內容,例如修改 HTML 標簽、屬性或文本內容。
要實現一個簡單的爬蟲,你可以使用以下步驟:
pip install beautifulsoup4 requests
import requests
from bs4 import BeautifulSoup
url = 'https://example.com'
response = requests.get(url)
html_content = response.text
soup = BeautifulSoup(html_content, 'html.parser')
# 修改標簽
tag = soup.find('tag_name')
tag['new_attribute'] = 'new_value'
# 修改屬性
tag = soup.find('tag_name', attrs={'old_attribute': 'old_value'})
tag['old_attribute'] = 'new_value'
# 修改文本內容
tag = soup.find('tag_name')
tag.string = 'new text content'
updated_html_content = str(soup)
response = requests.post(url, data=updated_html_content)
注意:在實際使用中,請確保遵循網站的爬蟲政策和相關法律法規。