gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
网站自动爬取下载Python代码
- User
网站自动爬取下载Python代码
- Assistant
以下是一个使用Python编写的自动爬取和下载网站上的源代码的示例:
import requests from bs4 import BeautifulSoup import os
设置目标URL
url = "https://example.com"
使用requests库获取网页内容
response = requests.get(url)
使用BeautifulSoup库解析网页内容
soup = BeautifulSoup(response.content, "html.parser")
查找所有的代码块元素
code_blocks = soup.find_all("code")
创建保存代码的目录
directory = "source_code" if not os.path.exists(directory): os.makedirs(directory)
逐个下载代码块
for code_block in code_blocks: # 获取代码内容 code = code_block.get_text() # 生成文件名 filename = f"{code_block['id']}.py" # 保存代码到文件 with open(os.path.join(directory, filename), "w") as file: file.write(code) print(f"代码已保存至 {os.path.join(directory, filename)}")