我用 python 编写了一个脚本,从网页上抓取不同帖子的前五个标题,然后将标题写入单独的文本文件,并将它们放在桌面文件夹中的五个不同子文件夹中DataStorage。
目前我的以下脚本可以解析五个帖子的标题并将它们写入五个不同的文本文件中,然后将它们放在桌面文件夹中DataStorage。
如何在一个主文件夹中创建五个不同的子文件夹并将文本文件放在相关的子文件夹中?
到目前为止,这是我的尝试:
import os
import requests
from bs4 import BeautifulSoup
url = "https://stackoverflow.com/questions/tagged/web-scraping"
dirf = r"C:\Users\WCS\Desktop\DataStorage" #The main folder in desktop
if not os.path.exists(dirf):os.makedirs(dirf)
os.chdir(dirf)
res = requests.get(url)
soup = BeautifulSoup(res.text,"lxml")
for item in soup.select(".summary .question-hyperlink")[:5]:
filename = item.text.split(" ")[0]
with open(filename+'.txt','w', encoding='utf-8') as filename:
filename.write(item.text)
肥皂起泡泡
精慕HU
相关分类