以下是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&quot;:&quot;,国内的保险员说风险太大,不受法律保护什么的。大神推荐我赴港买保险吗?&quot;,&quot;visitCount&quot
reg='editableDetail&quot;:&quot;([\s\S]*?)&quot;,&quot;visitCount&quot'
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代码的更多相关文章

  1. python学习之-用scrapy框架来创建爬虫(spider)

    scrapy简单说明 scrapy 为一个框架 框架和第三方库的区别: 库可以直接拿来就用, 框架是用来运行,自动帮助开发人员做很多的事,我们只需要填写逻辑就好 命令: 创建一个 项目 : cd 到需 ...

  2. 【Python实战】Scrapy豌豆荚应用市场爬虫

    对于给定的大量APP,如何爬取与之对应的(应用市场)分类.描述的信息?且看下面分解. 1. 页面分析 当我们在豌豆荚首页搜索框输入微信后,会跳转到搜索结果的页面,其url为http://www.wan ...

  3. scrapy 知乎用户信息爬虫

    zhihu_spider 此项目的功能是爬取知乎用户信息以及人际拓扑关系,爬虫框架使用scrapy,数据存储使用mongo,下载这些数据感觉也没什么用,就当为大家学习scrapy提供一个例子吧.代码地 ...

  4. Python开源爬虫项目代码:抓取淘宝、京东、QQ、知网数据--转

    数据来源:数据挖掘入门与实战  公众号: datadw scrapy_jingdong[9]- 京东爬虫.基于scrapy的京东网站爬虫,保存格式为csv.[9]: https://github.co ...

  5. 爬虫(十五):Scrapy框架(二) Selector、Spider、Downloader Middleware

    1. Scrapy框架 1.1 Selector的用法 我们之前介绍了利用Beautiful Soup.正则表达式来提取网页数据,这确实非常方便.而Scrapy还提供了自己的数据提取方法,即Selec ...

  6. 基于scrapy框架输入关键字爬取有关贴吧帖子

    基于scrapy框架输入关键字爬取有关贴吧帖子 站点分析 首先进入一个贴吧,要想达到输入关键词爬取爬取指定贴吧,必然需要利用搜索引擎 点进看到有四种搜索方式,分别试一次,观察url变化 我们得知: 搜 ...

  7. 使用scrapy制作的小说爬虫

    使用scrapy制作的小说爬虫 爬虫配套的django网站  https://www.zybuluo.com/xuemy268/note/63660 首先是安装scrapy,在Windows下的安装比 ...

  8. scrapy 知乎的模拟登陆及抓取用户数据

    最近看了python的scrapy 框架并用其抓取了部分知乎用户数据,代码主要是集中在知乎登陆和抓取时候的逻辑处理上. 1. 首先进入知乎登陆页面zhihu.com/#sigin上, 用xpath提取 ...

  9. 基于Python,scrapy,redis的分布式爬虫实现框架

    原文  http://www.xgezhang.com/python_scrapy_redis_crawler.html 爬虫技术,无论是在学术领域,还是在工程领域,都扮演者非常重要的角色.相比于其他 ...

随机推荐

  1. centos7.7下docker与k8s安装(DevOps三)

    1.系统配置 centos7.7 docker 1.13.1 centos7下安装docker:https://www.cnblogs.com/pu20065226/p/10536744.html 2 ...

  2. php URL处理函数

    parse_url()    basename()    pathinfo()    dirname() 用法 parse_url() 是一计算机函数,功能是解析一个 URL 并返回一个关联数组,包含 ...

  3. flutter 隐藏返回按钮 自定义返回按钮

    自定义返回按钮 //改变颜色 Widget build(BuildContext context) { return Scaffold( appBar: AppBar( leading: BackBu ...

  4. 匿名内部类 this.val$的问题

    一天偶尔在网上找到一个jar包,反编译后出现了如下的代码: public void defineAnonymousInnerClass(String name)  {    new Thread(na ...

  5. web开发(六) EL表达式

    在网上看见一篇不错的文章,写的详细. 以下内容引用那篇博文.转载于<http://www.cnblogs.com/whgk/p/6432044.html>,在此仅供学习参考之用. 一.EL ...

  6. 阶段3 2.Spring_04.Spring的常用注解_5 自动按照类型注入

    运行出现了空指针异常 @Autowired 注解出现的位置 AutoWired的代码 常用的就是写类上和方法上. 运行测试,刚才运行是一个空指针异常 也就是通过Autowired 这个accountD ...

  7. Flutter路由(一)

    第一点:push使用 1.pushNamed——Navigator.of(context).pushNamed('routeName') Navigator.of(context).pushNamed ...

  8. Could not find aapt Please set the ANDROID_HOME environment variable with the Android SDK root directory path

    写case写好好哒,突然debug的时候就冒出这个错误: selenium.common.exceptions.WebDriverException: Message: An unknown serv ...

  9. LeetCode.1010-歌曲总长度可被60整除的对数

    这是小川的第377次更新,第405篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第239题(顺位题号是1010).在歌曲列表中,第i首歌曲的持续时间为[i]秒. 返回其总 ...

  10. 网格UV展开

    原文链接 UV展开是什么 参数曲面的参数域变量一般用UV字母来表达,比如参数曲面F(u,v).所以一般叫的三维曲面本质上是二维的,它所嵌入的空间是三维的.凡是能通过F(u,v)来表达的曲面都是参数曲面 ...