首先,经过检查,确认需要查找的字符串确实存在于网页HTML代码中。
其次,确认使用Beautiful Soup的语法是否正确。需要使用合适的解析器,并对查找的内容加上标识符(如标签、class、id等),示例代码如下:
from bs4 import BeautifulSoup
#假定已经得到了HTML代码
html_doc = """
The Dormouse's story
The Dormouse's story
Once upon a time there were three little sisters; and their names were
Elsie,
Lacie and
Tillie;
and they lived at the bottom of a well.
...
"""
soup = BeautifulSoup(html_doc, 'html.parser')
my_string = soup.find('a', {'class': 'sister', 'id': 'link2'}).string
print(my_string)
在上述代码中,我们使用了html.parser
解析器,用以解析HTML代码。然后使用find函数查找a标签,并使用{'class': 'sister', 'id': 'link2'}
作为标识符,来找到指定的标签。
最后,使用.string
方法获取找到的标签包含的字符串内容。
使用以上步骤,可以避免Beautiful Soup中无法找到字符串的问题。