首页 文章

使用Python解析HTML

提问于
浏览
143

我正在寻找一个用于Python的HTML Parser模块,它可以帮助我以Python列表/字典/对象的形式获取标签 .

如果我有一份表格的文件:

<html>
<head>Heading</head>
<body attr1='val1'>
    <div class='container'>
        <div id='class'>Something here</div>
        <div>Something else</div>
    </div>
</body>
</html>

然后它应该给我一种通过HTML标签的名称或ID访问嵌套标签的方法,这样我基本上可以让它给我 div 标签中的内容/文本 body 包含在 body 标签中,或类似的东西 .

如果您使用过Firefox的“Inspect element”功能(查看HTML),您就会知道它以一种漂亮的嵌套方式为您提供所有标记,就像树一样 .

我更喜欢内置模块,但可能会有点太多 .


我在Stack Overflow和互联网上的一些博客上经历了很多问题,其中大多数都建议使用BeautifulSoup或lxml或HTMLParser,但其中很少有人详细介绍了这些功能,最后只是讨论哪一个更快/更有效 .

7 回答

  • 63

    因此我基本上可以要求它在div标签中为我提供内容/文本,其中包含body标签中包含的class ='container',或类似的东西 .

    try: 
        from BeautifulSoup import BeautifulSoup
    except ImportError:
        from bs4 import BeautifulSoup
    html = #the HTML code you've written above
    parsed_html = BeautifulSoup(html)
    print parsed_html.body.find('div', attrs={'class':'container'}).text
    

    我猜你不需要性能描述 - 只需阅读BeautifulSoup的工作原理 . 看看official documentation .

  • 34

    我想你要找的是pyquery

    pyquery:一个类似jquery的python库 .

    你想要的一个例子可能是:

    from pyquery import PyQuery    
    html = # Your HTML CODE
    pq = PyQuery(html)
    tag = pq('div#id') # or     tag = pq('div.class')
    print tag.text()
    

    它使用与Firefox或Chrome的检查元素相同的选择器 . 例如:

    the element selector is 'div#mw-head.noprint'

    被检查的元素选择器是'div#mw-head.noprint' . 所以在pyquery中,你只需要传递这个选择器:

    pq('div#mw-head.noprint')
    
  • 1

    在这里,您可以阅读有关Python中不同HTML解析器及其性能的更多信息 . 即使文章有点过时,它仍然给你一个很好的概述 .

    Python HTML parser performance

    我推荐BeautifulSoup,即使它没有内置 . 只是因为它很容易处理这些任务 . 例如:

    import urllib2
    from BeautifulSoup import BeautifulSoup
    
    page = urllib2.urlopen('http://www.google.com/')
    soup = BeautifulSoup(page)
    
    x = soup.body.find('div', attrs={'class' : 'container'}).text
    
  • 161

    与其他解析器库相比 lxml 非常快:

    使用 cssselect ,它也很容易用于抓取HTML页面:

    from lxml.html import parse
    doc = parse('http://www.google.com').getroot()
    for div in doc.cssselect('a'):
        print '%s: %s' % (div.text_content(), div.get('href'))
    

    lxml.html Documentation

  • 5

    我建议使用 lxml 来解析HTML . 见"Parsing HTML" (on the lxml site).

    根据我的经验,美丽的汤混淆了一些复杂的HTML . 我相信这是因为Beautiful Soup不是一个解析器,而是一个非常好的字符串分析器 .

  • 0

    我建议使用 justext 库:

    https://github.com/miso-belica/jusText

    用法: Python2:

    import requests
    import justext
    
    response = requests.get("http://planet.python.org/")
    paragraphs = justext.justext(response.content, justext.get_stoplist("English"))
    for paragraph in paragraphs:
        print paragraph.text
    

    Python3:

    import requests
    import justext
    
    response = requests.get("http://bbc.com/")
    paragraphs = justext.justext(response.content, justext.get_stoplist("English"))
    for paragraph in paragraphs:
        print (paragraph.text)
    
  • 22

    我会用EHP

    https://github.com/iogf/ehp

    这里是:

    from ehp import *
    
    doc = '''<html>
    <head>Heading</head>
    <body attr1='val1'>
        <div class='container'>
            <div id='class'>Something here</div>
            <div>Something else</div>
        </div>
    </body>
    </html>
    '''
    
    html = Html()
    dom = html.feed(doc)
    for ind in dom.find('div', ('class', 'container')):
        print ind.text()
    

    输出:

    Something here
    Something else
    

相关问题