要用Python編寫一個簡單的爬蟲,你可以使用requests庫來獲取網頁內容,然后使用BeautifulSoup庫來解析HTML并提取所需信息。以下是一個簡單的示例,用于抓取網站上的標題和鏈接:
首先,確保你已經安裝了requests和beautifulsoup4庫。如果沒有,請使用以下命令安裝:
pip install requests beautifulsoup4
接下來,創建一個名為simple_crawler.py的文件,并在其中編寫以下代碼:
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')
titles = soup.find_all('h2') # 根據網頁結構選擇合適的標簽
links = soup.find_all('a')
for title, link in zip(titles, links):
print(f"Title: {title.get_text().strip()}")
print(f"Link: {link['href']}")
print()
def main():
url = input("Enter the URL of the website you want to crawl: ")
html = get_page(url)
if html:
parse_page(html)
if __name__ == "__main__":
main()
將代碼中的h2和a標簽替換為你要抓取的網站結構的相應標簽。運行simple_crawler.py文件,然后輸入要抓取的網站URL。程序將輸出頁面上的標題和鏈接。
請注意,這只是一個簡單的示例,實際爬蟲可能需要處理更復雜的情況,例如處理分頁、登錄、JavaScript渲染的頁面等。對于更高級的爬蟲,可以考慮使用Scrapy框架。