首先,确保你已经正确地导入了BeautifulSoup。其次,检查你的选择器是否正确匹配了要查找的字符串,可能是因为选择器不正确导致无法找到。最后,你可以使用.find方法来查找字符串。例如:
from bs4 import BeautifulSoup
html_doc = """
My Title
My Heading
My paragraph.
Another paragraph.
"""
soup = BeautifulSoup(html_doc, 'html.parser')
# 确认soup已经初始化
assert soup is not None
# 使用find方法查找字符串
my_heading = soup.find('h1', text='My Heading')
print(my_heading.string)
输出将会是:
My Heading