以下是一个示例代码,演示了如何使用按.attr选择器进行测验:
import requests
from bs4 import BeautifulSoup
# 发送请求获取页面内容
url = 'https://example.com'
response = requests.get(url)
html = response.text
# 使用BeautifulSoup解析页面内容
soup = BeautifulSoup(html, 'html.parser')
# 使用按.attr选择器查找元素
# 例如,查找所有class为 "title" 的元素
elements = soup.select('.title')
# 打印找到的元素内容
for element in elements:
print(element.text)
在上面的示例中,我们首先使用requests库发送GET请求,将页面的内容保存在html变量中。然后,我们使用BeautifulSoup库将HTML内容解析为一个BeautifulSoup对象。
接下来,我们使用.select()方法并传入按.attr选择器(在这个例子中是.title),来查找所有匹配的元素。这个示例中,我们查找所有class为"title"的元素。
最后,我们遍历找到的元素,并打印它们的文本内容。根据具体的需求,你可以根据元素的不同属性来执行其他操作。