Python实现的爬取网易动态评论操作示例

yipeiwu_com6年前Python爬虫

本文实例讲述了Python实现的爬取网易动态评论操作。分享给大家供大家参考,具体如下:

打开网易的一条新闻的源代码后,发现并没有所要得评论内容。

经过学习后发现,源代码只是一个完整页面的“骨架”,而我所需要的内容是它的填充物,这时候需要打开工具里面的开发人员工具,从加载的“骨肉”里找到我所要的评论

圈住的是类型

找到之后打开网页,发现json类型的格式,用我已学过的正则,bs都不好闹,于是便去了解了正则,发现把json的格式换化成python的格式后,用列表提取内容是一条明朗的道路。。。

但是在细致分析的时候也发现了问题

从这里获得每条评论时,感觉有点不对,观察发现如果是回复评论的评论会出现他回复那条评论的数据,于是用正则提取了一下

最终的代码如下:

#coding=utf-8
__author__ = 'kongmengfan123'
import urllib
import re
import json
import time
def gethothtml(url):#最热评论
  page=urllib.urlopen(url)
  html=page.read()
  get_json(html)
def gethnewtml():#最新评论有5页
  for i in range(1,6):
    url = 'http://comment.news.163.com/api/v1/products/a2869674571f77b5a0867c3d71db5856/threads/C4QFIJNS0001875O/comments/newList?offset=%d&limit=30&showLevelThreshold=72&headLimit=1&tailLimit=2&callback=getData&ibc=newspc&_=1478010624978'%i*30
    page = urllib.urlopen(url)
    html=page.read()
    time.sleep(1)
    get_json(html)
def get_json(json_):
  end_=re.compile(r'\);')#将json网页转化成python数据
  begain=re.compile(r'getData\(')
  json_=begain.sub('',json_)
  json_=end_.sub('',json_)
  ajson=json.loads(json_)
  lis=ajson["commentIds"]#获得每条评论的键
  n=0
  for i in range(1,len(lis)):
    try:
      xulie=re.compile('\d{10,}')#取得准确评论的键(去掉回复)
      bia=re.findall(xulie,lis[n])
      w.write(ajson['comments'][bia[len(bia)-1]]['user']['nickname'].encode('utf-8')+'|')
    except KeyError:
      w.write(ajson['comments'][bia[len(bia)-1]]['user']['location'].encode('utf-8')+'|')
    if (len(lis[n])>13):
      xulie=re.compile('\d{10,}')
      bia=re.findall(xulie,lis[n])
      w.write(ajson['comments'][bia[len(bia)-1]]['content'].encode('utf-8')+'\n')
    else:
       w.write(ajson['comments'][lis[n]]['content'].encode('utf-8')+'\n')
    n=n+1
  return lis
w=open('wangyi.txt','w')
w.write('用户名'+'|'+'热门评论'+'\n')
hot_=gethothtml('http://comment.news.163.com/api/v1/products/a2869674571f77b5a0867c3d71db5856/threads/C4QFIJNS0001875O/comments/hotList?offset=0&limit=40&showLevelThreshold=72&headLimit=1&tailLimit=2&callback=getData&ibc=newspc')
w.write('用户名'+'|'+'最新评论'+'\n')
gethnewtml()
w.close()

成功。

更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

python requests爬取高德地图数据的实例

如下所示: 1.pip install requests 2.pip install lxml 3.pip install xlsxwriter import requests #想...

使用BeautifulSoup爬虫程序获取百度搜索结果的标题和url示例

熟悉Java的jsoup包的话,对于Python的BeautifulSoup库应该很容易上手。 复制代码 代码如下:#coding: utf-8import sysimport urll...

Python爬虫:将headers请求头字符串转为字典的方法

原生请求头字符串 raw_headers = """Host: open.tool.hexun.com Pragma: no-cache Cache-Control: no-cach...

Python中利用aiohttp制作异步爬虫及简单应用

Python中利用aiohttp制作异步爬虫及简单应用

摘要: 简介 asyncio可以实现单线程并发IO操作,是Python中常用的异步处理模块。关于asyncio模块的介绍,笔者会在后续的文章中加以介绍,本文将会讲述一个基于asyncio...

Python多进程方式抓取基金网站内容的方法分析

本文实例讲述了Python多进程方式抓取基金网站内容的方法。分享给大家供大家参考,具体如下: 在前面这篇/post/162418.htm我们已经简单了解了”python的多进程”,现在我...