在 Visual Studio Code (VSCode) 中編寫 Python 爬蟲,你可以遵循以下步驟:
安裝 Python 和 VSCode 確保你已經安裝了 Python 和 VSCode。如果沒有,請訪問 https://www.python.org/downloads/ 下載并安裝 Python,然后從 https://code.visualstudio.com/ 下載并安裝 VSCode。
創建項目文件夾 在你的計算機上創建一個新的文件夾,用于存放你的爬蟲項目。例如,你可以創建一個名為 “my_crawler” 的文件夾。
打開 VSCode 并創建新文件 打開 VSCode,然后點擊左上角的 “文件” 菜單,選擇 “打開文件夾”。瀏覽到你剛剛創建的 “my_crawler” 文件夾,然后點擊 “打開”。
創建一個新的 Python 文件 在 VSCode 的左側邊欄中,點擊 “文件資源管理器” 圖標,然后在 “my_crawler” 文件夾中創建一個新的 Python 文件。你可以為其命名為 “spider.py” 或任何你喜歡的名稱。
編寫爬蟲代碼
在 “spider.py” 文件中編寫你的爬蟲代碼。以下是一個簡單的使用 requests
和 BeautifulSoup
庫的爬蟲示例:
import requests
from bs4 import BeautifulSoup
def get_html(url):
try:
response = requests.get(url)
response.raise_for_status()
response.encoding = response.apparent_encoding
return response.text
except Exception as e:
print(f"獲取網頁失?。?span class="hljs-subst">{e}")
return None
def parse_html(html):
soup = BeautifulSoup(html, "html.parser")
# 在這里編寫解析 HTML 的代碼
return []
def main():
url = "https://example.com"
html = get_html(url)
if html:
data = parse_html(html)
print(data)
if __name__ == "__main__":
main()
requests
和 BeautifulSoup
庫:pip install requests
pip install beautifulsoup4
python spider.py
現在你已經成功創建了一個簡單的 Python 爬蟲。你可以根據需要修改代碼以滿足你的需求。如果你需要使用其他庫,如 Scrapy
或 Selenium
,請確保已將其安裝在 VSCode 的終端中。