python编程,利用BS和re下载某网站的文本信息分数信息。参考地址豆瓣书评:" https://book.douban.com/subject/1084306/comments/ "
时间: 2024-11-01 20:22:58 浏览: 33
在Python中,你可以使用BeautifulSoup (BS) 库来解析HTML内容,以及正则表达式 (re) 来提取特定的信息。这里是一个简单的步骤说明如何从给定的豆瓣读书评论页面下载文本信息和评分:
首先,你需要安装必要的库,如果还没有安装,可以使用pip:
```bash
pip install beautifulsoup4 requests
```
然后,编写一个Python脚本来完成这个任务:
```python
import requests
from bs4 import BeautifulSoup
import re
# 目标URL
url = "https://book.douban.com/subject/1084306/comments/"
def get_html(url):
try:
response = requests.get(url)
response.raise_for_status()
return response.text
except requests.exceptions.RequestException as e:
print(f"请求出错: {e}")
return None
def parse_text_score(html_content):
soup = BeautifulSoup(html_content, 'lxml')
# 提取评论部分
comment_area = soup.find('div', class_='comment-item')
# 提取评分
score = soup.find('span', itemprop='ratingValue').text.strip()
# 提取文本信息
text = comment_area.find('p').text.strip()
# 使用正则匹配提取评分后的文字(例如,“来自某人的评语”)
match = re.search(r'\((.*?)\)', text)
if match:
text = text[:match.start()] if match else text
return score, text
# 获取并处理HTML
html_content = get_html(url)
if html_content is not None:
score, text = parse_text_score(html_content)
print(f"评分: {score}, 文本信息: {text}")
else:
print("无法获取数据")
阅读全文