【发布时间】:2017-12-01 09:02:10
【问题描述】:
我想使用 bs4 搜索带有特定字符串的第一个标签,并从搜索中排除标题标签。根据bs4 doc,它支持正则表达式。
为什么下面的代码不起作用:
#!/usr/bin/env python
from bs4 import BeautifulSoup
import re
html_doc = """
<html>
<head>
<title>The Dormouse's story</title>
</head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<div class="title">The Dormouse's story</div>
</body>
</html>
"""
soup = BeautifulSoup(html_doc, 'html.parser')
title = soup.find(name=re.compile("^title"), string="The Dormouse's story")
if title is not None:
print("String found:", title)
else:
print("String not found.")
# returns: String found: <title>The Dormouse's story</title>
(我希望代码能找到<b>The Dormouse's story</b> 标签。)
bs4/Python 是否需要特殊的正则表达式语法?
注意:我不想要替代代码建议。我想知道我的代码是否有问题,或者 bs4 是否不支持正则表达式,这与文档所说的相反。
【问题讨论】:
标签: python regex string python-3.x beautifulsoup