【问题标题】:Grabbing the info from beautiful soup and putting it into a text file?从美丽的汤中获取信息并将其放入文本文件?
【发布时间】:2012-10-17 23:00:48
【问题描述】:

我已经开始学习如何使用 urllib 和 beautifulsoup 从网站上抓取信息。我想从该页面(在代码中)获取所有文本并将其放入文本文件中。

import urllib
from bs4 import BeautifulSoup as Soup
base_url = "http://www.galactanet.com/oneoff/theegg_mod.html"



url = (base_url)
soup = Soup(urllib.urlopen(url))

print(soup.get_text())

当我运行它时,它会抓取文本,尽管它在所有字母之间用空格输出它并且仍然显示 HTML,但不确定为什么。

i   n   '   >      Y   u   p   .       B   u   t       d   o   n      t       f   e   e        

这样,有什么想法吗?

另外,我该怎么做才能将此信息放入文本文件中?

(使用 beautifulsoup4 并运行 ubuntu 12.04 和 python 2.7)

谢谢你:)

【问题讨论】:

    标签: python beautifulsoup urllib


    【解决方案1】:

    我在编码方面遇到了一些问题,所以我稍微更改了您的代码,然后添加了将结果打印到文件的部分:

    import urllib
    from bs4 import BeautifulSoup as Soup
    
    base_url = "http://www.galactanet.com/oneoff/theegg_mod.html"
    
    url = (base_url)
    content = urllib.urlopen(url)
    soup = Soup(content)
    # print soup.original_encoding
    theegg_text = soup.get_text().encode("windows-1252")
    
    f = open("somefile.txt", "w")
    f.write(theegg_text);
    f.close()
    

    【讨论】:

      【解决方案2】:

      你可以试试html2text:

      import html2text as htmlconverter
      print htmlconverter.html2text('<HTML><BODY>HI</BODY></HTML>')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-01-19
        • 2018-02-20
        • 2021-05-24
        • 2018-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多