scrapy 知乎关键字爬虫spider代码
以下是spider部分的代码。爬知乎是需要登录的,建议使用cookie就可以了,如果需要爬的数量预计不多,请不要使用过大的线程数量,否则会过快的被封杀,需要等十几个小时账号才能重新使用,比起损失的这十几个小时的时间,即使是单线程也能够爬取很多页面了,得不偿失。 知乎是基于账号策略反爬的,换ua和ip并没用,如果需要高并发,需要采用几十个账号的方式来爬取。
# -*- coding: utf-8 -*-
import scrapy
from scrapy import Request
from scrapy import log
import logging
#from zhihu.items import ZhihuItem
from zhihu.items import ZhihuItem
from scrapy_redis.spiders import RedisSpider
import re
import json
import time class BaoxianSpider(RedisSpider): ##使用redis分布式 name = "baoxian"
allowed_domains = ["zhihu.com"]
#redis_key='baoxian:start_urls'
keywords='软件测试' ###要爬的关键词
from urllib import quote
urlencode_keywords=quote(keywords) start_urls = ['https://www.zhihu.com/r/search?q='+urlencode_keywords+'&type=content&offset=0'] #'https://www.zhihu.com/r/search?q=%E4%BF%9D%E9%99%A9&type=content&offset=0'
def start_requests(self):
for url in self.start_urls:
yield Request(url=url, callback=self.parse,dont_filter=True) def parse(self, response):
body=response.body #{"paging":{"next":"\/r\/search?q=%E4%BF%9D%E9%99%A9&type=content&offset=50"},"htmls"
#print body #获取问题链接
question_href_reg=r'<div class=\\"title\\"><a target=\\"_blank\\" href=\\"\\/question\\/(.*?)\\"'
all_question_href=re.findall(question_href_reg,body)
print 'all_question_href:',all_question_href
for aqh in all_question_href:
question_href='https://www.zhihu.com/question/'+str(aqh)
yield Request(url=question_href, callback=self.parse_question,dont_filter=True)
print question_href log.msg("question_href:%s \n list_question_page:%s"%(question_href,response.url), level=log.INFO)
#self.log
#获取下一页的链接 reg=r'{"paging":{"next":"(\\/r\\/search\?q=.*?&type=content&offset=.*?)"},"htmls"'
next_page=re.findall(reg,body)
print '下一页问题:',next_page
if len(next_page):
#print next_page[0] #https://www.zhihu.com/r/search?q=%E4%BF%9D%E9%99%A9&type=content&offset=10
next_page_url='https://www.zhihu.com'+ next_page[0].replace('\\','')
print 'next_page_url:',next_page_url
yield Request(url=next_page_url, callback=self.parse,dont_filter=True)
log.msg("next_page_url:%s"%next_page_url, level=log.INFO) #data-type=\"Answer\"><div class=\"title\"><a target=\"_blank\" href=\"\/question\/22316395\" def parse_question(self,response): ####问题详情页面
#print response.body print 'response.url:',response.url
title=response.xpath('//h1[@class="QuestionHeader-title"]/text()').extract_first()
print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
print 'title:',title
#editableDetail":",国内的保险员说风险太大,不受法律保护什么的。大神推荐我赴港买保险吗?","visitCount"
reg='editableDetail":"([\s\S]*?)","visitCount"'
content_match=re.findall(reg,response.body)
if content_match:
content=content_match[0]
else:
content='' #有可能问题无具体描述
print 'content:',content
question={}
question['url']=response.url
question['title']=title question['content']=content
#https://www.zhihu.com/question/19904068
question['comment']=[]
#https://www.zhihu.com/api/v4/questions/20214716/answers?sort_by=default&include=data%5B%2A%5D.is_normal%2Cis_sticky%2Ccollapsed_by%2Csuggest_edit%2Ccomment_count%2Ccollapsed_counts%2Creviewing_comments_count%2Ccan_comment%2Ccontent%2Ceditable_content%2Cvoteup_count%2Creshipment_settings%2Ccomment_permission%2Cmark_infos%2Ccreated_time%2Cupdated_time%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%2Cupvoted_followees%3Bdata%5B%2A%5D.author.is_blocking%2Cis_blocked%2Cis_followed%2Cvoteup_count%2Cmessage_thread_token%2Cbadge%5B%3F%28type%3Dbest_answerer%29%5D.topics&limit=3&offset=3
answer_json='https://www.zhihu.com/api/v4/questions/'+re.findall('(\d+)',response.url)[0]+'/answers?sort_by=default&include=data%5B%2A%5D.is_normal%2Cis_sticky%2Ccollapsed_by%2Csuggest_edit%2Ccomment_count%2Ccollapsed_counts%2Creviewing_comments_count%2Ccan_comment%2Ccontent%2Ceditable_content%2Cvoteup_count%2Creshipment_settings%2Ccomment_permission%2Cmark_infos%2Ccreated_time%2Cupdated_time%2Crelationship.is_authorized%2Cis_author%2Cvoting%2Cis_thanked%2Cis_nothelp%2Cupvoted_followees%3Bdata%5B%2A%5D.author.is_blocking%2Cis_blocked%2Cis_followed%2Cvoteup_count%2Cmessage_thread_token%2Cbadge%5B%3F%28type%3Dbest_answerer%29%5D.topics&limit=20&offset=0'
print 'answer_json:',answer_json
yield Request(url=answer_json, callback=self.parse_json,meta=question,dont_filter=False)
"""
item=ZhihuItem()
item['title']=question['title']
item['url']=question['url']
item['content']=question['content']
yield item
print item
""" def parse_json(self,response): ####答案列表
meta=response.meta
dict=json.loads(response.body) #print 'dict:',dict
print 'dcit to json:',json.dumps(dict,ensure_ascii=False)
comment_list=meta['comment']
for data in dict['data']: # dict['data']是列表,每个元素是字典
try:
comment_dict={}
comment_dict['comment_content']=data['content']
if data['author']['name']:
comment_dict['author']=data['author']['name']
else:
comment_dict['author']=''
comment_dict['voteup_count']=data['voteup_count']
comment_dict['comment_count']=data['comment_count']
comment_dict['comment_time']=time.strftime('%Y-%m-%d',time.localtime(data['created_time']))
comment_list.append(comment_dict)
except Exception,e:
print e
meta['comment']=comment_list
meta['answer_num']=dict['paging']['totals'] if dict['paging']['is_end']==False: ###自动翻页
yield Request(url=dict['paging']['next'], callback=self.parse_json,meta=meta,dont_filter=False)
else:
#log.msg("last:%s"%next_page_url, level=log.INFO)
print 'last:',meta['title'],meta['url'] ,meta['content'],meta['answer_num'],len(meta['comment'])#,meta['comment']
item=ZhihuItem()
item['title']=meta['title']
item['url']=meta['url']
item['content']=meta['content']
item['answer_num']=meta['answer_num']
item['comment']=meta['comment']
yield item
发下运行结果,存储用的mongodb

comment的内容

scrapy 知乎关键字爬虫spider代码的更多相关文章
- python学习之-用scrapy框架来创建爬虫(spider)
scrapy简单说明 scrapy 为一个框架 框架和第三方库的区别: 库可以直接拿来就用, 框架是用来运行,自动帮助开发人员做很多的事,我们只需要填写逻辑就好 命令: 创建一个 项目 : cd 到需 ...
- 【Python实战】Scrapy豌豆荚应用市场爬虫
对于给定的大量APP,如何爬取与之对应的(应用市场)分类.描述的信息?且看下面分解. 1. 页面分析 当我们在豌豆荚首页搜索框输入微信后,会跳转到搜索结果的页面,其url为http://www.wan ...
- scrapy 知乎用户信息爬虫
zhihu_spider 此项目的功能是爬取知乎用户信息以及人际拓扑关系,爬虫框架使用scrapy,数据存储使用mongo,下载这些数据感觉也没什么用,就当为大家学习scrapy提供一个例子吧.代码地 ...
- Python开源爬虫项目代码:抓取淘宝、京东、QQ、知网数据--转
数据来源:数据挖掘入门与实战 公众号: datadw scrapy_jingdong[9]- 京东爬虫.基于scrapy的京东网站爬虫,保存格式为csv.[9]: https://github.co ...
- 爬虫(十五):Scrapy框架(二) Selector、Spider、Downloader Middleware
1. Scrapy框架 1.1 Selector的用法 我们之前介绍了利用Beautiful Soup.正则表达式来提取网页数据,这确实非常方便.而Scrapy还提供了自己的数据提取方法,即Selec ...
- 基于scrapy框架输入关键字爬取有关贴吧帖子
基于scrapy框架输入关键字爬取有关贴吧帖子 站点分析 首先进入一个贴吧,要想达到输入关键词爬取爬取指定贴吧,必然需要利用搜索引擎 点进看到有四种搜索方式,分别试一次,观察url变化 我们得知: 搜 ...
- 使用scrapy制作的小说爬虫
使用scrapy制作的小说爬虫 爬虫配套的django网站 https://www.zybuluo.com/xuemy268/note/63660 首先是安装scrapy,在Windows下的安装比 ...
- scrapy 知乎的模拟登陆及抓取用户数据
最近看了python的scrapy 框架并用其抓取了部分知乎用户数据,代码主要是集中在知乎登陆和抓取时候的逻辑处理上. 1. 首先进入知乎登陆页面zhihu.com/#sigin上, 用xpath提取 ...
- 基于Python,scrapy,redis的分布式爬虫实现框架
原文 http://www.xgezhang.com/python_scrapy_redis_crawler.html 爬虫技术,无论是在学术领域,还是在工程领域,都扮演者非常重要的角色.相比于其他 ...
随机推荐
- git提交到分支
git checkout grego@gregoo:mygo$ git checkout origin/test Note: checking out 'origin/test'. You are i ...
- "Developer tools access" 需控制另一个进程才能继续调试 解决方案
解决方案: 打开终端输入下边命令: DevToolsSecurity --status 查看状态 DevToolsSecurity --enable 输入密码,修改为enable,即可用 DevToo ...
- Word模板替换
package com.sisa.auweb.tools.bookmarkprocess; import org.apache.poi.openxml4j.opc.OPCPackage; import ...
- 基于 Linux Bridge 的 Neutron 多平面网络实现原理
目录 文章目录 目录 前言 前文列表 多平面网络 Local(本地网络) Flat(扁平网络) 配置 Flat 网络 VLAN 配置 VLAN 网络 VxLAN 配置 VxLAN 网络 GRE 前言 ...
- Selenium 2自动化测试实战6(异常)
一.异常 python用异常队形(exception object)来表示异常情况,遇到错误后,会引发异常.如果异常对象并未被处理和捕捉,则程序就会用所谓的回溯(Traceback,一种错误信息)来终 ...
- 拉取代码产生冲突 && 切换分支
1.拉取代码产生冲突 项目中用的主要是 IDEA 编辑器,拉取代码时产生冲突的时候,就先 add + commit 一下,然后再拉取代码,这样子就不冲突了. 拉取过后再push一次. 2.切换一个新增 ...
- Message的定义類型
SAP通过Message来回执程序的执行状态.使用Tcode:SE91. SAP將Message分为不同的类,如下图显示为ZF环境下ZMM01类相关Message列表. Message short t ...
- 网易云课堂_C++程序设计入门(下)_期末考试_期末考试在线编程题目
期末考试在线编程题目 返回考试 本次考试题目一共两个,在考试期间可以不限制次数地提交 温馨提示: 1.本次考试属于Online Judge题目,提交后由系统即时判分. 2.学生可以在考试截止时间 ...
- 关于vtkCommand的各种事件的解释
superclass for callback/observer methods vtkCommand is an implementation of the observer/command des ...
- oop理论
三大特性: 封装:把对象的属性和行为独立的一个整体,并尽可能的隐藏对象内部实现细节.增加安全性. 继承:从已有的类中派生出新的类,称为子类,子类继承父类的属性和行为,并能根据自己的需求扩展出新的行为. ...