Python: Saving BeautifulSoup Output to Text file

拟墨画扇 提交于 2020-01-04 11:43:03

问题


This question is a follow-up to this question here.

I am parsing a txt file in Python as follow:

text = open("C:\\Users\\0001193125-13-416534.txt")
soup = BeautifulSoup(text.read().lower())
for type_tag in soup.find_all('TYPE', text=re.compile('^\s*(?:EX|XML)', re.I)):
    type_tag.extract()

Once I have extracted all the <TYPE> tags from soup, how can I save the ouptut to a txt file? I have tried:

with io.open("C:\\Output.txt", 'a', encoding='utf8') as logfile:
    for tr in soup.find_all('tr')[2:]:
        tds = tr.find_all('td')
        logfile.write(u"%s, %s, %s\n" % (tds[0].text, tds[1].text, tds[2].text))

as suggested here but no success. I end up with an empty output.txt file.

来源:https://stackoverflow.com/questions/27048178/python-saving-beautifulsoup-output-to-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!