要在Python中爬取網頁并創建文件,可以按照以下步驟進行:
import requests
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"的文件。你可以根據需要自定義文件路徑和名稱。