如何解决NavigableString写入文件时的TypeError错误?
嘿,我一眼就揪出问题所在了!你打开文件时把文件实例存在了file_object变量里,但循环写入的时候却用了file.write(all)——这里的file是Python内置的文件类,不是你实际打开的那个文件对象,所以才会抛出这个错误。
快速修复代码
先修正变量名的问题,同时为了让内容换行显示,记得给每个写入的内容加个换行符,另外显式把NavigableString转成字符串更稳妥:
file_object = open("name-list.txt", "w") #Opening the file name = soup.find(class_='table-responsive') #Extracting the data name_list = name.find_all('td') #Refining the data for final in name_list: content = final.contents[0] #Final result # 修正变量名+转字符串+加换行 file_object.write(str(content) + '\n') file_object.close()
更优雅的写法(推荐)
用with语句可以自动帮你管理文件的打开和关闭,不用手动调用close(),避免忘记关闭文件的问题:
with open("name-list.txt", "w") as file_object: name = soup.find(class_='table-responsive') name_list = name.find_all('td') for final in name_list: content = final.contents[0] file_object.write(str(content) + '\n')
顺便解决你之前的CSV需求
你提到之前用csv库没法逐行添加,其实可以直接把表格数据写入CSV,比先写TXT再提取高效多了。假设你的表格是标准的行结构(tr为行,td为列),可以这样写:
import csv with open("data.csv", "w", newline='') as csv_file: writer = csv.writer(csv_file) # 获取表格的所有行 table_rows = soup.find(class_='table-responsive').find_all('tr') for row in table_rows: # 提取当前行的所有单元格内容,转成字符串列表 row_content = [str(td.contents[0]) for td in row.find_all('td')] writer.writerow(row_content)
这样生成的CSV文件直接就能用表格软件打开,不用再额外处理TXT啦!
内容的提问来源于stack exchange,提问作者Ishaan Pathak
相关产品推荐
相关产品推荐

