我正在尝试在H2标签中的标题下刮擦文本,该标题以“ ...的好处”开头...因此它可能像“玩具的好处”或“杯子的好处”等。
html代码是:
<h2 class="DrugOverview__title___1OwgG">Benefits of Toys</h2>
我到目前为止使用的代码是
benfit = soup.find('h2',text='Benefits of')
q = benefit.get_text(strip=True)
我该如何解决?还请记住,在这种情况下,h2类不能用于抓取(由于其他问题)。
我们可以使用正则表达式来获取一些特定的字符串
我用作strs
输入html内容
使用以下代码:
import re
strs = '<h2 class="DrugOverview__title___1OwgG">Benefits of Toys</h2><h2 class="DrugOverview__title___1OwgG">Benefits of kids</h2>'
soup = BeautifulSoup(strs, 'html.parser')
pattern = re.compile(r'Benefits of')
benefit = soup.findAll(text = pattern)
print(benefit)
输出:
['Benefits of Toys', 'Benefits of kids']
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句