将beautifulsoup输出写入.txt的问题

时间:2014-03-07 14:50:27

标签: python web-scraping beautifulsoup

我正在使用beautifulsoup抓取网页文章。输出正确打印,但未将完整输出写入文件。一旦它达到引用的句子,它似乎就会破裂。以下是相关代码。任何见解都会非常有用。

使用此网址复制结果:http://www.reuters.com/article/2014/03/06/us-syria-crisis-assad-insight-idUSBREA250SD20140306

import urllib2
from bs4 import BeautifulSoup
import re
import codecs

# Ask user to enter URL
url = raw_input("Please enter a valid URL: ")

# Make sure file is clear for new content
open('ctp_output.txt', 'w').close()

# Open txt document for output
txt = open('ctp_output.txt', 'w')

# Parse HTML of article, aka making soup
soup = BeautifulSoup(urllib2.urlopen(url).read())

# retrieve all of the paragraph tags
with open('ctp_output.txt', 'w'):
    for tag in soup.find_all('p'):
        txt.write(tag.text.encode('utf-8') + '\n' + '\n')

# Close txt file with new content added
txt.close()

3 个答案:

答案 0 :(得分:1)

有几个问题:

for tag in tags:
    f.write(tag.get_text() + '\n' + '\n')

需要进一步缩进(它应该是with open('ctp_output.txt', 'w') as f:的孩子;

txt.close()

是多余的 - with语句已经确保文件被关闭;

我没有看到输出中缺少任何内容 - 你能引用一个消失的句子吗?

编辑:这看起来像是一个Python3问题 - 它在Python 2.7.5中完美运行

用str.decode()修复

Edit2:


您的代码可以简化为

from bs4 import BeautifulSoup

import sys
if sys.hexversion < 0x3000000:
    # Python 2.x
    from urllib2 import urlopen
    inp = raw_input
else:
    # Python 3.x
    from urllib.request import urlopen
    inp = input

def get_paras(url):
    page = urlopen(url).read().decode('utf-8')
    soup = BeautifulSoup(page)
    return [para.get_text() for para in soup('p')]

def write_lst(f, lst, fmt="{}\n\n".format):
    for item in lst:
        f.write(fmt(item))

def main():
    url   = inp("Please enter a fully qualified URL: ")
    fname = inp("Please enter the output file name: ")

    with open(fname, "w") as outf:
        write_lst(outf, get_paras(url))

if __name__=="__main__":
    main()

答案 1 :(得分:0)

我的猜测是你应该编写你想用utf8编写的内容:

to_write = tag.get_text() + "\n"
f.write(to_write.encode("utf-8"))

这是我最近的pb。

答案 2 :(得分:0)

如果您在 Hugh Bothwell 修改后获得UnicodeEncodeError: 'ascii' codec can't encode characters in position 21-23: ordinal not in range(128),那么也请执行以下操作

使用codecs.open()io.open()使用适当的文本编码(即encoding =“...”)打开文本文件,而不是使用open()打开字节文件。

fp=codecs.open('ctp_output.txt', 'w',encoding="utf-8")

然后写下

fp.write("what you want to write")

您需要import codecs才能获得此作品