我已经用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)
最佳答案
以下可能有效
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]
curr_dir = os.path.join(dirf, filename)
os.makedirs(curr_dir)
filepath = os.path.join(curr_dir, filename+'.txt')
with open(filepath, 'w', encoding='utf-8') as f:
f.write(item.text)