要用Python編寫爬蟲代碼,你可以使用一些流行的庫,如Requests和BeautifulSoup。以下是一個簡單的示例,展示了如何使用這兩個庫抓取一個網頁的內容并提取所需的信息。
首先,確保你已經安裝了Requests和BeautifulSoup庫。如果沒有,請使用以下命令安裝:
pip install requests
pip install beautifulsoup4
接下來,創建一個名為simple_crawler.py
的Python文件,并在其中編寫以下代碼:
import requests
from bs4 import BeautifulSoup
def get_page(url):
response = requests.get(url)
if response.status_code == 200:
return response.text
else:
print(f"Error: Unable to fetch the page. Status code: {response.status_code}")
return None
def parse_page(html):
soup = BeautifulSoup(html, 'html.parser')
# 在此處提取所需的信息,例如:
title = soup.find('title').text
print(f"Page Title: {title}")
def main():
url = input("Enter the URL of the webpage you want to crawl: ")
html = get_page(url)
if html:
parse_page(html)
if __name__ == "__main__":
main()
在這個示例中,我們首先導入所需的庫,然后定義了三個函數:
get_page(url)
:發送一個GET請求到指定的URL,并返回網頁的HTML內容。如果請求失敗,它將打印錯誤信息并返回None。parse_page(html)
:使用BeautifulSoup解析HTML內容,并提取所需的信息。在這個示例中,我們提取了網頁的標題。main()
:從用戶那里獲取要抓取的網頁URL,調用get_page()
函數獲取HTML內容,然后調用parse_page()
函數解析內容并提取信息。最后,我們在if __name__ == "__main__":
語句中調用main()
函數,以便在運行此腳本時執行爬蟲代碼。
要運行此示例,請在命令行中輸入以下命令:
python simple_crawler.py
然后按照提示輸入要抓取的網頁URL。腳本將輸出網頁的標題。你可以根據需要修改parse_page()
函數以提取其他信息。