共計 665 個字符,預計需要花費 2 分鐘才能閱讀完成。
要在 Python 中爬取網頁并創建文件,可以按照以下步驟進行:
- 導入必要的庫:
import requests
- 發送 GET 請求以獲取網頁內容:
url = "https://www.example.com" # 替換成要爬取的網頁鏈接
response = requests.get(url)
- 檢查響應狀態碼,確保請求成功:
if response.status_code == 200:
# 繼續處理響應內容
else:
print("請求失敗")
- 創建文件并將網頁內容寫入文件:
file_path = "output.html" # 替換成要創建的文件路徑和名稱
with open(file_path, "w", encoding="utf-8") as file:
file.write(response.text)
完整的代碼示例:
import requests
url = "https://www.example.com" # 替換成要爬取的網頁鏈接
response = requests.get(url)
if response.status_code == 200:
file_path = "output.html" # 替換成要創建的文件路徑和名稱
with open(file_path, "w", encoding="utf-8") as file:
file.write(response.text)
print("文件創建成功")
else:
print("請求失敗")
此代碼將爬取指定網頁的內容,并將內容保存為一個名為 ”output.html” 的文件。你可以根據需要自定義文件路徑和名稱。
丸趣 TV 網 – 提供最優質的資源集合!
正文完