【问题标题】:Strip values from HTML with beautifulsoup使用 beautifulsoup 从 HTML 中去除值
【发布时间】:2019-02-07 04:45:14
【问题描述】:

试图剥离

<h3 class="s-item__title s-item__title--has-tags" role="text"><div><div class="s-item__title-tag">Nov 14, 2018</div></div>Text I Want</h3>

我想要以下值: 2018 年 11 月 14 日, 我想要的文字

我已经尝试过,但无法达到第二个值。

【问题讨论】:

  • 请同时发布您的python代码,以便我们为您提供帮助

标签: python beautifulsoup


【解决方案1】:

我使用strings generator 来抓取html中的所有字符串,并存储在一个列表中:

from bs4 import BeautifulSoup

html = """<h3 class="s-item__title s-item__title--has-tags" role="text"><div><div class="s-item__title-tag">Nov 14, 2018</div></div>Text I Want</h3>)"""

bs = BeautifulSoup(html, 'html.parser')
text = [s for s in bs.h3.strings]

text

['Nov 14, 2018', 'Text I Want']

【讨论】:

  • 很好,我喜欢这种方法!您还可以添加一些列表组合以获得更好的效果:text = [s for s in bs.h3.strings]
  • 太棒了,非常感谢 :) 并且完全同意你对列表 comp 的看法——刚刚更新了我的答案以包含它!谢谢!
  • 我很高兴@ToddS,很高兴你发现它很有用——如果你觉得它完全解决了你的问题,你介意将它标记为accepted answer吗?谢谢!
猜你喜欢
  • 2011-03-31
  • 1970-01-01
  • 1970-01-01
  • 2021-03-29
  • 1970-01-01
  • 2011-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多