gpt4 book ai didi

python - 在 Python 中使用 .write() 只会写入一行

转载 作者:行者123 更新时间:2023-11-30 22:25:07 25 4
gpt4 key购买 nike

因此,作为 Thenewboston 的一项任务,我试图从他的网站上获取一段代码并将其写入文件。代码抓取部分工作正常,但编写部分不起作用:

import requests
from bs4 import BeautifulSoup


def crawler(url):
source = requests.get(url)
source_text = source.text
soup_obj = BeautifulSoup(source_text, "html.parser")
for code in soup_obj.find('code'):
codes = str(code)
final_code = codes.replace('<br/>', '').replace('Â', '')
print(final_code)
fx = open('crawler_code.txt', 'w')
fx.write(final_code)
fx.close()

crawler('https://thenewboston.com/forum/topic.php?id=1610')

最佳答案

您正在循环中覆盖文件

在循环写入之前打开文件进行写入

with open('crawler_code.txt', 'w') as fx:
for code in soup_obj.find('code'):
codes = str(code)
final_code = codes.replace('<br/>', '').replace('Â', '')
print(final_code)
fx.write(final_code)

关于python - 在 Python 中使用 .write() 只会写入一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47627193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com