python读取景区评论数据,并存放在txt中
时间: 2023-06-22 22:32:23 浏览: 93
好的,你可以按照以下步骤来读取景区评论数据并将其存放在txt文件中:
1. 首先,你需要安装requests库和beautifulsoup4库。你可以使用以下命令来进行安装:
```
pip install requests
pip install beautifulsoup4
```
2. 然后,你可以使用requests库来获取景区评论数据。以携程为例,你可以使用以下代码来获取携程某个景区的评论数据:
```python
import requests
url = "https://you.ctrip.com/sight/xxx.html" # xxx为景区ID
response = requests.get(url)
```
3. 接着,你可以使用beautifulsoup4库来解析HTML页面,并获取评论数据。以获取评论内容为例,你可以使用以下代码:
```python
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, "html.parser")
comments = soup.find_all("div", class_="comment_txt")
for comment in comments:
content = comment.find("span", class_="heightbox").text.strip()
print(content)
```
4. 最后,你可以将获取到的评论数据存放在txt文件中。以将评论数据存放在comments.txt文件中为例,你可以使用以下代码:
```python
with open("comments.txt", "w", encoding="utf-8") as f:
for comment in comments:
content = comment.find("span", class_="heightbox").text.strip()
f.write(content + "\n")
```
以上就是读取景区评论数据并存放在txt文件中的步骤,你可以根据自己的需求进行修改。
阅读全文
相关推荐













