some other text
使用Beautifulsoup和正则表达式来查找HTML文档中的元素。以下是一个示例代码,它查找一个id为"content"的div元素,该元素包含一个文本字符串"my_string":
from bs4 import BeautifulSoup
import re
html_doc = """
The Dormouse's story
my_stringsome other text
"""
soup = BeautifulSoup(html_doc, 'html.parser')
# Find the div element with id "content" that contains the string "my_string"
pattern = re.compile(r'.*my_string.*')
div_element = soup.find('div', {'id': 'content'}, text=pattern)
print(div_element)
输出:
my_stringsome other text
首先,使用Beautifulsoup解析HTML文档。然后,使用正则表达式来定义要查找的字符串模式。最后,使用find()方法查找包含该模式的div元素。