在Python中使用.write()只写一行

在Python中使用.write()只写一行,python,web-crawler,file-writing,Python,Web Crawler,File Writing,因此,作为NewBoston的一项任务,我试图从他的站点获取一段代码并将其写入文件。代码获取部分工作正常,但编写部分不工作: import requests from bs4 import BeautifulSoup def crawler(url): source = requests.get(url) source_text = source.text soup_obj = BeautifulSoup(source_text, "html.parser")

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

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')
导入请求
从bs4导入BeautifulSoup
def爬虫(url):
source=requests.get(url)
source\u text=source.text
soup\u obj=BeautifulSoup(源文本,“html.parser”)
对于soup_obj.find(“代码”)中的代码:
代码=str(代码)
最终代码=代码。替换('
','')。替换('t','') 打印(最终代码) fx=open('crawler\u code.txt','w') fx.编写(最终代码) fx.close() 爬虫https://thenewboston.com/forum/topic.php?id=1610')
您并没有真正提到问题所在,但我认为,当您为要抓取的每一行打开文件时(因此使用
'w'
模式删除内容),您在文件末尾只写了一行。这是你的问题吗


如果是这样,请尝试在爬网方法开始时在循环之前打开文件。

您正在覆盖循环中的文件

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

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)
打开('crawler_code.txt',w')作为fx:
对于soup_obj.find(“代码”)中的代码:
代码=str(代码)
最终代码=代码。替换('
','')。替换('t','') 打印(最终代码) fx.编写(最终代码)
您遇到的错误是什么,请通过编辑移动
打开
关闭
循环外的行在
w
模式下打开文件会删除内容,从而说明问题本身。