【问题标题】:How to scrape the body from a webpage?如何从网页中抓取正文?
【发布时间】:2013-04-02 21:13:06
【问题描述】:

我有一个代码,可以从 ESPN NCAA 网站提取标题。但我想刮掉整个网页。我是编码新手,如果您能帮助抓取网页,我将不胜感激。我发现很难理解 XML 标记并识别它们。请你们中的任何人修改此代码,以便打印此网页上的全部或大部分内容吗?谢谢!

from urllib import urlopen
from BeautifulSoup import BeautifulSoup
import smtplib


site = urlopen('http://espn.go.com/college-football').read()
soup = BeautifulSoup(site)    


for i in soup.findAll('ul', {'class': 'headlines'}):
    for tag in i.findAll('li'):
        for a in tag.findAll({'a' : True, 'title' : False}):            
            print a.text
            print a['href']                                
            print "\n"

【问题讨论】:

  • 代码看起来不错。您有什么具体问题吗?
  • 是的。我想问的是,上面的代码只提取了标题。如何让它提取网页中的所有文字?

标签: python web-scraping beautifulsoup


【解决方案1】:

您也可以使用html2text 作弊:)

【讨论】:

    【解决方案2】:

    如果您只想提取文本内容,可以使用继承自 HTMLParser 的类(来自标准库):

    from HTMLParser import HTMLParser
    from StringIO import StringIO                                                             
    
    class DeHTMLParser(HTMLParser):
        def __init__(self):
            HTMLParser.__init__(self)
            self.text = StringIO()
        def handle_data(self, data):
            self.text.write(data.strip())
    
    def text_from_html(html):
        parser = DeHTMLParser()
        parser.feed(html)
        parser.close()
        return parser.text.getvalue()
    

    当遇到 HTML 树中的文本内容时,会调用 DeHTMLParser 类的 handle_data 函数。这些函数只是将值附加到 StringIO 对象(不进行字符串连接以避免创建多个临时对象)。 text_from_html 使用该类从字符串/unicode 中获取文本(查看HTMLParser 模块文档以获取更多信息)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-29
      • 1970-01-01
      • 2016-08-26
      • 2020-06-18
      • 1970-01-01
      相关资源
      最近更新 更多