从python到txt文件为不同的URL输出多个f.write('x')命令

时间:2018-03-31 18:34:34

标签: python beautifulsoup spyder

我正在尝试收集文件一和文件二并输出文件一和文件二到一个文本文件。但是,我的代码返回到文本文件仅限于文件一的文本。如何为文件1和文件2输出f.write(bio.text)?我想计算机必须有一种方法可以将它们作为独立请求读取,这样它就可以在另一个命令之后执行一个命令,文件文件中的文件一下面列出了文件二。

#File one
import requests
from bs4 import BeautifulSoup
url = 'https://philosophy.nd.edu/people/faculty/anjan-chakravartty/'
response = requests.get(url)
html = response.content
soup = BeautifulSoup(html,'html.parser')

bio = soup.find(class_='faculty-bio')

#file one output

f = open('philospohy.json', 'w')

f.write(bio.text)
f.close()


#File two

url = 'https://philosophy.nd.edu/people/faculty/patricia-blanchette/'
response = requests.get(url)
html = response.content
soup = BeautifulSoup(html,'html.parser')

bio = soup.find(class_='faculty-bio')


#File two output
f = open('philospohy.json', 'w')
f.write(bio.text)
f.close()

1 个答案:

答案 0 :(得分:2)

f = open(‘philospohy.json’, ‘w’)改为f = open(‘philospohy.json’, ‘a’, encoding = “utf8”)两行,它应该有效。原因是当您使用w模式打开文件时,它会清除整个文件,然后写入文件。使用a模式,它只会在结尾添加新文本。还添加了encoding = “utf8”,因为所有字符都不是ASCII。

相关问题