将Python BeatifoulSoup的结果保存到文件



我试图保存从维基百科URL提取/解析文本到文本文件的BeatifoulSoup迭代的结果。我没有成功地创建文本文件并添加文本,而我正在循环上迭代以解析句子。我想把我的代码输出到一个文本文件。印刷到屏幕工作良好。希望你能指点我。

import requests
import string
from bs4 import BeautifulSoup
url_to_text = "https://en.wikipedia.org/wiki/Santiago"
url_open = requests.get(url_to_text)
soup = BeautifulSoup(url_open.content,'html.parser')
for i in range(1,50):
doc_text = print((soup('p')[i].text))

请尝试一下,

with open(file="my_text.txt", mode="w", encoding="UTF-8") as dest_file:
for i in range(1, 50):
dest_file.write(soup('p')[i].text)

问题主要是由于编码。默认情况下,Python使用UNICODE。切换到UTF-8就可以了。如果问题仍然存在,请随时与我们联系。

谢谢。

如何写文件:

with open('text.txt', 'w') as file:
file.write('text')

你可以阅读这个问题来获得更多关于如何在Python中保存文件的信息。

实现:

from requests import get
from bs4 import BeautifulSoup
soup = BeautifulSoup(
get("https://en.wikipedia.org/wiki/Santiago").content, "html.parser"
)
# mode w = writing mode
with open(file="text.txt", mode="w",encoding="utf-8") as file:
for line in range(1, 50):
file.write(soup("p")[line].text)

我想补充的是,在执行之前没有必要存在文件,如果它不存在,Python将创建它。

最新更新