【问题标题】:Python - getting text from htmlPython - 从 html 获取文本
【发布时间】:2012-04-21 05:21:48
【问题描述】:

如何以一种不错的方式从这个 html 代码中提取文本“ROYAL PYTHON”? 我一直在寻找解决方案 4 小时,但没有发现任何真正相关且有效的解决方案。

<div class="definicja"><a href="javascript: void(0);"
onclick="play('/mp3/1/81/c5ebfe33a08f776931d69857169f0442.mp3')"
class="ikona_sluchaj2"></a> <a href="/slownik/angielsko_polski/,royal+python">ROYAL
PYTHON</a></div>

【问题讨论】:

  • 我会使用 BeautifulSoup。在其他新闻中,中间那些随机的直角括号在做什么?

标签: python html text


【解决方案1】:

正如 Joel Cornett 所说,像这样使用BeautifulSoup

from bs4 import BeautifulSoup

html = '''<div class="definicja"><a href="javascript: void(0);" onclick="play('/mp3/1/81/c5ebfe33a08f776931d69857169f0442.mp3')" class="ikona_sluchaj2"></a> <a href="/slownik/angielsko_polski/,royal+python">ROYAL PYTHON</a></div>'''

soup = BeautifulSoup(html)
print soup.getText()

【讨论】:

    【解决方案2】:

    你可以使用lxml和xpath:

    from lxml.html.soupparser import fromstring
    
    s = 'yourhtml'
    h = fromstring(s)
    print h.xpath('//div[@class="definicja"]/a[2]/text()')[0]
    

    【讨论】:

      【解决方案3】:

      在这里假设一些事情:(1) HTML sn-p 将始终是有效的 XHTML,并且 (2) 您正在寻找 sn-p 中第二个锚标记内的文本

      from xml.dom.minidom import parseString
      
      htmlString = """<pre><div class="definicja"><a href="javascript: void(0);" onclick="play('/mp3/1/81/c5ebfe33a08f776931d69857169f0442.mp3')" class="ikona_sluchaj2"><img src="/images/ikona_sluchaj2.gif" alt=""/></a> <a href="/slownik/angielsko_polski/,royal+python">ROYAL PYTHON</a></div></pre>"""
      
      xmlDoc = parseString(htmlString)
      anchorNodes = xmlDoc.getElementsByTagName("a")
      secondAnchorNode = anchorNodes[1]
      textNode = secondAnchorNode.childNodes[0]
      
      print textNode.nodeValue
      

      xml 包含在 Python 中,因此您不必担心安装任何包。

      【讨论】:

        【解决方案4】:

        还有标准模块 xml.etree.ElementTree

        import xml.etree.ElementTree as ET
        
        fragment = '''<pre>
        <div class="definicja"><a href="javascript: void(0);"
          onclick="play('/mp3/1/81/c5ebfe33a08f776931d69857169f0442.mp3')"
          class="ikona_sluchaj2"><img src="/images/ikona_sluchaj2.gif" alt=""
          /></a> <a href="/slownik/angielsko_polski/,royal+python">ROYAL
          PYTHON</a></div>
        </pre>'''
        
        frg = ET.fromstring(fragment)
        for a in frg.findall('div/a'):
            if a.text is not None:
                print a.text
                print '------'
                print ' '.join(a.text.split())  # all words to one line
        

        它打印在我的控制台上

        ROYAL
          PYTHON
        ------
        ROYAL PYTHON
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-03-24
          • 1970-01-01
          • 1970-01-01
          • 2011-07-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多