爬取起点中文网里面遮天的评论并保存到txt
时间: 2023-09-11 20:05:50 浏览: 42
好的,以下是一个简单的示例代码,可以爬取起点中文网《遮天》小说的评论并将其保存到txt文件中:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://book.qidian.com/info/1004608738#Catalog'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
comment_url = 'https:' + soup.select_one('.discuss-wrap .discuss-header .more')['href']
r = requests.get(comment_url)
soup = BeautifulSoup(r.text, 'html.parser')
comments = []
for item in soup.select('.review-wrap .review-item'):
user = item.select_one('.review-username').text.strip()
content = item.select_one('.review-content').text.strip()
comments.append(user + ': ' + content + '\n')
with open('comments.txt', 'w', encoding='utf-8') as f:
f.writelines(comments)
```
这个代码首先使用requests库和BeautifulSoup库获取《遮天》小说的评论页面的URL。然后,从评论页面中提取每条评论的用户名和内容,并将其保存到一个列表中。最后,将这些评论保存到名为“comments.txt”的文件中。
需要注意的是,为了正确解析评论页面的URL,我们需要先从小说信息页面中获取评论URL的后缀,然后使用相对地址获取完整的评论URL。此外,我们在保存评论到文件时,使用了“w”模式来打开文件,这意味着每次运行代码时,文件都会被覆盖。如果您希望将新的评论添加到现有文件中而不是覆盖它,请使用“a”模式来打开文件。