python爬取评论_python爬取网易评论
时间: 2023-10-04 18:08:13 浏览: 53
可以使用 Python 的 requests 库和 BeautifulSoup 库来爬取网易评论。以下是一个简单的示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 网易新闻页面URL
url = 'https://news.163.com/21/1125/15/GT1L2I2P000189FH.html'
# 发送请求获取页面内容
r = requests.get(url)
html = r.text
# 解析页面内容获取评论
soup = BeautifulSoup(html, 'html.parser')
comments = soup.find_all('div', {'class': 'item-box'})
# 打印评论
for comment in comments:
print(comment.find('div', {'class': 'text'}).text)
```
需要注意的是,网易评论通常需要登录才能查看,因此如果要爬取登录后的评论,需要使用一些额外的技术,比如模拟登录或者使用网易评论的API。
相关问题
python爬取歌词_利用Python网络爬虫抓取网易云音乐歌词
好的,下面是回答:
是的,利用Python网络爬虫可以抓取网易云音乐歌词。具体步骤如下:
1. 打开网易云音乐网站,搜索需要下载歌词的歌曲,并复制歌曲的ID。
2. 构造歌词页面的URL,URL的格式为:https://music.163.com/#/song?id=歌曲ID。
3. 利用Python的requests库向URL发送请求,获取歌词页面的HTML代码。
4. 利用正则表达式或者BeautifulSoup库解析HTML代码,获取歌词的文本内容。
5. 将歌词文本保存到本地文件中。
需要注意的是,网易云音乐网站有反爬虫机制,需要设置请求头部信息,模拟浏览器进行访问。同时,对于一些需要登录后才能访问的歌曲,需要先进行登录操作才能进行爬取。
希望能对你有所帮助!
python爬取网易云评论_Python - 网易云热门评论爬取
下面是一个简单的Python爬取网易云音乐评论的示例代码,仅供参考:
``` python
import requests
import json
import time
import random
import pandas as pd
def get_comments(song_id, offset):
url = 'http://music.163.com/api/v1/resource/comments/R_SO_4_{}/?limit=100&offset={}'.format(song_id, offset)
headers = {
'Referer': 'http://music.163.com/song?id={}'.format(song_id),
'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'}
res = requests.get(url, headers=headers)
data = json.loads(res.text)
comments = data['comments']
return comments
def main(song_id):
comments_list = []
for i in range(1, 21):
comments = get_comments(song_id, i * 100)
for comment in comments:
comment_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(comment['time'] / 1000))
comments_list.append([comment['user']['nickname'], comment_time, comment['content']])
time.sleep(random.randint(2, 5))
df = pd.DataFrame(comments_list, columns=['user', 'time', 'content'])
df.to_csv('comments.csv', index=False)
if __name__ == '__main__':
main('歌曲ID')
```
需要将代码中的`歌曲ID`替换为实际需要爬取的歌曲ID,运行后会在当前目录下生成一个名为`comments.csv`的文件,包含了歌曲的评论用户、评论时间和评论内容。需要注意的是,为了防止被封IP,这里加入了随机的睡眠时间。