Python 当我将结果写入文本文件时,只会出现一段
我目前正在编写一个应用程序,使用requests和BeautifulSoup从网站上收集信息。现在我正试图将这些信息放在一个文本文件中,我设法做到了,但文本文件中只插入了一个段落 现在我正在使用basicfile命令来完成这项工作,但它没有起作用。我已经在网上搜索了其他方法,但在我的代码中没有任何方法起作用Python 当我将结果写入文本文件时,只会出现一段,python,Python,我目前正在编写一个应用程序,使用requests和BeautifulSoup从网站上收集信息。现在我正试图将这些信息放在一个文本文件中,我设法做到了,但文本文件中只插入了一个段落 现在我正在使用basicfile命令来完成这项工作,但它没有起作用。我已经在网上搜索了其他方法,但在我的代码中没有任何方法起作用 import requests from bs4 import BeautifulSoup r = requests.get("https://en.wikipedia.org/wiki/
import requests
from bs4 import BeautifulSoup
r = requests.get("https://en.wikipedia.org/wiki/Somalia")
soup = BeautifulSoup(r.text)
for p in soup.find_all('p'):
print(p.text)
file = open("Research.txt", "w")
file.write(p.text)
file.close()
提前谢谢你 要么是问题中的格式错误,要么是f.write方法在for循环之外。以下代码应该可以工作:
import requests
from bs4 import BeautifulSoup
r = requests.get("https://en.wikipedia.org/wiki/Somalia")
soup = BeautifulSoup(r.text)
with open("Research.txt", 'a') as f: # 'a' code stands for 'append'
for p in soup.find_all('p'):
f.write(f"{p.text}\n")
注意:如果您不理解with open语句,请查看:
NB2:f-string格式ie:f{p.text}\n仅适用于python3.6+。如果您有以前的版本,请将其替换为{}\n.formatp.text
您发布的代码只打印最后一段,因为它是循环迭代的最后一项。下面的代码写入了所有段落:
with open("Research.txt", "w") as f:
for p in soup.find_all('p'):
f.write(p.text)
正如其他人指出的,您的写操作不在循环中。一个简单的解决办法是:
import requests
from bs4 import BeautifulSoup
r = requests.get("https://en.wikipedia.org/wiki/Somalia")
soup = BeautifulSoup(r.text)
mytext = ""
for p in soup.find_all('p'):
print(p.text)
mytext += p.text
file = open("Research.txt", "w")
file.write(mytext)
file.close()
这主要与您当前的代码类似,但在循环中构造一个字符串,然后将其写入文件。您的file.write语句不在循环中,因为您的打印在循环中。您的文件写入在循环之外,应该只获取pHello@Carcigenicate的最后一个值,您能告诉我如何使用语法吗?谢谢这不适用于我的特定页面,但其他工作!非常感谢。