【问题标题】:BeautifulSoup output to .txt fileBeautifulSoup 输出到 .txt 文件
【发布时间】:2016-07-02 13:59:55
【问题描述】:

我正在尝试将我的数据导出为 .txt 文件

from bs4 import BeautifulSoup
import requests
import os

import os

os.getcwd()
'/home/folder'
os.mkdir("Probeersel6") 
os.chdir("Probeersel6")
os.getcwd()
'/home/Desktop/folder'
os.mkdir("img")  #now `folder` 

url = "http://nos.nl/artikel/2093082-steeds-meer-nekklachten-bij-kinderen-door-gebruik-tablets.html"
r  = requests.get(url)
soup = BeautifulSoup(r.content)
data = soup.find_all("article", {"class": "article"})

with open(""%s".txt", "wb" %(url)) as file:
    for item in data:
        print item.contents[0].find_all("time", {"datetime": "2016-03-16T09:50:30+0100"})[0].text 
        print item.contents[0].find_all("a", {"class": "link-grey"})[0].text
        print "\n"
        print item.contents[0].find_all("img", {"class": "media-full"})[0]
        print "\n"
        print item.contents[1].find_all("div", {"class": "article_textwrap"})[0].text
        file.write()

应该放什么:

file.write()

上班?

我还试图让 .txt 文件的名称与 url 相同,我应该使用字符串吗?

with open(""%s".txt", "wb" %(url)) as file:


url = "http://nos.nl/artikel/2093082-steeds-meer-nekklachten-bij-kinderen-door-gebruik-tablets.html"

【问题讨论】:

    标签: python operating-system beautifulsoup python-requests bs4


    【解决方案1】:

    你应该把你的内容放在file.write里面。我可能会做类似的事情:

    #!/usr/bin/python3
    #
    
    from bs4 import BeautifulSoup
    import requests
    
    url = 'http://nos.nl/artikel/2093082-steeds-meer-nekklachten-bij-kinderen-door-gebruik-tablets.html'
    file_name=url.rsplit('/',1)[1].rsplit('.')[0]
    
    r  = requests.get(url)
    soup = BeautifulSoup(r.content, 'lxml')
    data = soup.find_all('article', {'class': 'article'})
    
    
    content=''.join('''{}\n{}\n\n{}\n{}'''.format( item.contents[0].find_all('time', {'datetime': '2016-03-16T09:50:30+0100'})[0].text,
                                                   item.contents[0].find_all('a', {'class': 'link-grey'})[0].text,
                                                   item.contents[0].find_all('img', {'class': 'media-full'})[0],
                                                   item.contents[1].find_all('div', {'class': 'article_textwrap'})[0].text,
                                                 ) for item in data)
    
    with open('./{}.txt'.format(file_name), mode='wt', encoding='utf-8') as file:
        file.write(content)
    

    【讨论】:

    • 它显示“UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 130: ordinal not in range(128)”
    • 我实际上没有访问python的权限,而且您似乎使用的是python2(我猜)。你应该阅读一点关于编码的知识,你的问题很常见!
    • 完全没有,但是编码和python3有点不同,所以我很久没用python2了。我会看看你的问题,但也许你使用二进制模式是对的wb
    • 我猜不是wb,最后一句有错误:item.contents[1].find_all("div", {"class": "article_textwrap"})[0] .text,在内容+= ' ' '
    • 在python2上你可以让文本模式如我所说,只需使用...text.decode('utf-8','replace')来解码内容。请注意,字符编码utf-8 可能并不总是相同的,您可能可以从 html 内容中解析它。我认为您的脚本还有其他一些小问题,但我真的没有时间调试它。
    【解决方案2】:

    我正在做一个网页抓取项目,这个问题给我带来了很多问题。我尝试了几乎每个处理Python编码的解决方案(使用string.encode()转换为UTF,转换为ASCII,使用'unicodedata'模块转换,使用.decode()然后.编码(),献血蒂姆彼得斯等)。

    没有一个解决方案一直有效,这让我觉得非常不符合 Python 风格。

    所以我最终使用的是以下内容:

    html = bs.prettify()  #bs is your BeautifulSoup object
    with open("out.txt","w") as out:
        for i in range(0, len(html)):
            try:
                out.write(html[i])
            except Exception:
                1+1
    

    它并不完美,但它给了我最好的结果。当我在浏览器中打开它时,它几乎每次都能正确解析页面。

    【讨论】:

    • 您的解决方案并非一直有效,因为您没有正确编码和解码您的输入和出口。通常您应该阅读 html 文档的编码。为了您的好运(或每个人的好运),几乎​​所有内容都在utf-8 或拉丁编码:)
    • @rsm 是的,但问题不在于解析 HTML 页面,它总是在写入文件时。操作系统通常以简单的 ASCII 格式存储文件,从 UTF-8 转换为 ASCII 很痛苦。可以通过open("out.txt","w","utf-8") 打开文件将文件编码设置为 UTF-8,但实际上这对我来说并不常见。我只是从实际经验中说,我发现上述解决方案是“有效”的解决方案。
    • Utf 问题已“解决”我认为stackoverflow.com/questions/36044653/… 现在需要解决.txt 文件的问题.. 或者.. 我错了吗?
    • 好吧,如果我不想讨论它,我很抱歉,但是那里的文档太多了。编码是程序的一个非常重要的部分,有时也很痛苦,但对我来说,python3 可以完成这项工作。如果您想知道 html 文件的字符集,只需查看元字符集 <meta charset="utf-8">..
    • @abhidivekar 顺便说一句,我只是仔细查看了您的代码,我不建议任何人使用该代码。没有理由拥有forrangeException1+1。你可以简单地使用类似out.write(html.encode('utf-8','replace'))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 2018-02-18
    • 2013-03-07
    • 1970-01-01
    • 2021-06-24
    • 2021-12-23
    相关资源
    最近更新 更多