下面是一个使用BeautifulSoup搜索.text属性的代码示例:
from bs4 import BeautifulSoup
# 假设网页内容如下
html = """
Welcome to my website
Here is some text that you can search for.
Another paragraph with more text.
"""
# 创建BeautifulSoup对象
soup = BeautifulSoup(html, 'html.parser')
# 使用.select方法选择所有包含文本的标签
tags_with_text = soup.select('body *:contains("text")')
# 打印每个标签的文本内容
for tag in tags_with_text:
print(tag.text)
输出结果为:
Here is some text that you can search for.
Another paragraph with more text.
在这个例子中,我们先使用BeautifulSoup解析HTML字符串创建了一个BeautifulSoup对象。然后,使用.select方法选择所有包含文本"text"的标签。最后,通过访问每个标签的.text属性,我们可以获取到它们的文本内容并打印出来。