python爬取携程网评论.
时间: 2023-11-05 22:03:08 浏览: 125
爬取携程网评论可以使用Python中的网络爬虫库,比如Requests和BeautifulSoup。下面是一种实现方式:
1. 首先,导入相关库:
```python
import requests
from bs4 import BeautifulSoup
```
2. 使用Requests库发送请求,获取携程网某个酒店的评论页面:
```python
url = "https://you.ctrip.com/hotels/某个酒店ID/reviews"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"}
response = requests.get(url, headers=headers)
```
请将"某个酒店ID"替换为你想要爬取评论的酒店ID。
3. 使用BeautifulSoup库解析HTML页面,提取评论内容:
```python
soup = BeautifulSoup(response.text, "html.parser")
comments = soup.find_all("div", class_="comment_single")
for comment in comments:
content = comment.p.text.strip()
print(content)
```
通过查看网页源代码,可以确定评论内容所在的HTML标签和类名,并使用find_all方法进行提取。此处假设评论内容位于class为"comment_single"的div标签内,而实际情况可能有所不同,请根据实际情况进行调整。
4. 由于携程网的评论可能存在多页,可以使用循环进行多页爬取:
```python
page = 1
while True:
url = "https://you.ctrip.com/hotels/某个酒店ID/reviews/p" + str(page)
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
comments = soup.find_all("div", class_="comment_single")
if not comments:
break
for comment in comments:
content = comment.p.text.strip()
print(content)
page += 1
```
这段代码中使用了一个while循环,当发现评论为空时,跳出循环。循环每次请求的url通过拼接字符串的方式实现翻页。
以上就是Python爬取携程网评论的简单实现方法,可以根据实际需求进行扩展和改进。