【问题标题】:extracting a string from html using HTMLParser & Python2.7使用 HTMLParser & Python2.7 从 html 中提取字符串
【发布时间】:2017-07-31 22:24:38
【问题描述】:

我正在开发一项 Alexa 技能,因此,我有可供我们使用的标准 Python (2.7) 库。因此,我没有可以使用的 BeautifulSoup4。

我正在尝试在完整的 HTML 页面中识别以下字符串,然后从以下内容中提取字符串“104 个空格”。 “104 个空格”是一个变量,但其他代码保持不变:-

<p class="jp1"><strong>Car Parking</strong>104 spaces</p>

这是否可以通过 HTMLParser 来完成,或者,这可以使用正则表达式搜索来完成吗?我很欣赏正则表达式不是解析 HTML 代码的最佳选择,但是考虑到我使用 urllib2 将 HTML 代码作为字符串处理,并且我希望提取一个特定字符串,该字符串遵循其中的特定字符串,在这种情况下可能就足够了。

我正在考虑的一个选项是:-

s1 = "<strong>Car Parking</strong>104 spaces</p>"
s2 = "<strong>Car Parking</strong>"

print s1[s1.index(s2) + len(s2):]

这将返回所有以“104 个空格”开头的文本。因此,如何隔离这段特定的文本?

谢谢

【问题讨论】:

    标签: python html regex string python-2.7


    【解决方案1】:

    我不使用 python,但这里是一个正则表达式。之后你需要用python手动替换strong和p标签应该很容易。

    var test = '<p class="jp1"><strong>Car Parking</strong>104 spaces</p>'
    
    test = test.match(/[<][/]strong[>](.*)[<][/]p[>]/gmi)
    //console.log would be here test:  [ '</strong>104 spaces</p>' ]
    test = test.join('')
    test = test.replace('</strong>','')
    test = test.replace('</p>','')
    
    console.log('test: ', test)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-07
      • 2015-05-08
      • 1970-01-01
      • 1970-01-01
      • 2020-02-28
      • 2012-09-24
      • 2014-05-20
      • 2019-02-07
      相关资源
      最近更新 更多