【问题标题】:python html strip of hyperlinked text only仅包含超链接文本的python html条
【发布时间】:2014-05-24 20:11:41
【问题描述】:

所以我试图从

中删除 HTML
<a href="/define.php?term=dubstep&defid=5175360">dubstep</a> the music that is created from transformers having s$#

所以解析后是这样的

dubstep - 由具有 S$# 的变形金刚创作的音乐

我想从这个html超链接中提取文本dubstep

我该怎么做呢?

我在这里阅读了解决方案 How to remove tags from a string in python using regular expressions? (NOT in HTML)

但我明白了

<class 'NameError'>, NameError("name 're' is not defined",), <traceback object at 0x036A41E8>)

【问题讨论】:

  • 您是否使用import re 导入了re 模块?

标签: python html strip


【解决方案1】:

为什么不使用BeautifulSoup

In [44]: from bs4 import  BeautifulSoup

In [45]: soup = BeautifulSoup ('''<a href="/define.php?term=dubstep&defid=5175360">dubstep</a> the music that is created from transformers having s$#''')

In [46]: soup.find('a').text
Out[46]: u'dubstep'

编辑:

或者如果你只想要文本:

In [48]: soup.text 
Out[48]: u'dubstep the music that is created from transformers having s$#'

【讨论】:

    【解决方案2】:

    很好

     NameError("name 're' is not defined",),
    

    表示你一开始忘了import re,但这是猜测。

    另外,由于您只需要 &lt;a&gt;&lt;/a&gt; 标记之间的单词,因此您需要一个类似于此的正则表达式:

     .*<a .*>([^<]*)</a>.*
    

    【讨论】:

      【解决方案3】:

      使用这个:

      from bs4 import Beautifulsoup
      html = <a href="/define.php?term=dubstep&defid=5175360">dubstep</a> the music that is created from transformers having s$#
      soup = Beautifulsoup(html)
      print(soup.get_text())
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多