以下是一個使用 Python 實現網絡爬蟲的簡單範例:
import requestsfrom bs4 import BeautifulSoupurl = "https://www.example.com"response = requests.get(url)if response.status_code == 200:soup = BeautifulSoup(response.content, 'html.parser')links = soup.find_all('a')for link in links:print(link.get('href'))else:print("Error: Could not retrieve content from URL.")這個例子中,我們使用 requests 庫發送 HTTP GET 請求到一個網站,然後使用 BeautifulSoup 庫對網頁內容進行解析。接著,我們使用 find_all() 方法查找網頁中的所有超鏈接,並打印它們的 URL。如果請求失敗,則輸出錯誤信息。
當然,這只是網絡爬蟲的簡單範例,實際使用中還需要考慮到許多方面,例如網站的反爬機制、數據的處理和儲存等等。在使用網絡爬蟲時,請遵守網站的使用條款和相關法律法規。
沒有留言:
張貼留言