文章标题1
文章内容1
要从更深层次的HTML中提取信息,可以使用BeautifulSoup库的find_all()方法结合CSS选择器来定位所需的元素。以下是一个包含代码示例的解决方法:
from bs4 import BeautifulSoup
# 假设有以下HTML代码
html = '''
文章标题1
文章内容1
文章标题2
文章内容2
'''
# 创建BeautifulSoup对象
soup = BeautifulSoup(html, 'html.parser')
# 使用CSS选择器查找所有带有class为'post'的div元素
posts = soup.find_all('div', class_='post')
# 遍历每个post元素,并提取标题和内容
for post in posts:
title = post.find('h2', class_='title').text
content = post.find('p', class_='content').text
print(f'标题:{title}')
print(f'内容:{content}')
print('--------')
运行以上代码将输出:
标题:文章标题1
内容:文章内容1
--------
标题:文章标题2
内容:文章内容2
--------
这里使用了find_all()方法来查找所有带有class为'post'的div元素,并使用find()方法在每个post元素中查找标题和内容的子元素。可以根据实际需求调整CSS选择器和属性名来提取所需的信息。