在上一篇博客中,我们得到了html源代码,并保存在变量text中,本篇,将带你解析这个代码:
首先,使用BeautifulSoup解析text内容:
soup = BeautifulSoup(text, 'html.parser')
接着,提取其中的内容:
soup = BeautifulSoup(text, 'html.parser')
# 提取所有标题和日期信息
texts_and_dates = []
for tag in soup.find_all('a', href=True):
# 标题
tag_content = tag.text.strip()
# 日期
date_span = tag.find_next('span', class_='rq1')
if date_span:
date_text = date_span.text.strip()
else:
date_text = ''
date_text = date_text.strip('[]')
# 添加到texts_and_dates中
texts_and_dates.append({'date': date_text, 'text': tag_content})
print(texts_and_dates)