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 爬虫技术,无论是在学术领域,还是在工程领域,都扮演者非常重要的角色.相比于其他 ...
随机推荐
- 开源之TinyPinyin
适用于Java和Android的快速.低内存占用的汉字转拼音库. https://github.com/promeG/TinyPinyin
- 写python获取android设备的GPS及姿态信息
在android上,我们可以使用QPython来编写.执行Python脚本.它对很多android 系统函数进行了方便的封装,使用QPython编写功能简单的小程序异常方便. 这个示例是我之前用来读取 ...
- ElasticSearch第五步-.net平台下c#操作ElasticSearch详解
前面我们讲解了关于ElasticSearch的安装配置,以及CRUD 本章我将讲解怎么使用c#操作ElasticSearch. 首先你需要一定的技术储备,比如:asp.net webapi,mvc,j ...
- 三十六:数据库之SQLAlchemy外建之一对一关系
relationship()的uselist参数默认为True,即一对多,如果要一对一,则需让uselist=False 准备工作 from sqlalchemy import create_engi ...
- pycryptodom的源码安装
1.去网站https://pypi.python.org/pypi/pycryptodome/#downloads下载 2.python setup.py build -> python set ...
- LeetCode.941-有效山形数组(Valid Mountain Array)
这是悦乐书的第360次更新,第387篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第222题(顺位题号是941).给定一个整数数组A,当且仅当它是一个有效的山形数组时返回 ...
- python 并发编程 协程 gevent模块
一 gevent模块 gevent应用场景: 单线程下,多个任务,io密集型程序 安装 pip3 install gevent Gevent 是一个第三方库,可以轻松通过gevent实现并发同步或异步 ...
- UML(统一建模语言)包含9种图
UML分为静态图.动态图 动态图:虚壮活血 () 静态图:租用配对累()
- HDU 1171 Big Event in HDU (动态规划、01背包)
Big Event in HDU Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others ...
- Hbase 0.92.1 Replication
原集群 服务器名称 服务 sht-sgmhadoopnn-01 Master,NameNode,JobTracker sht-sgmhadoopdn-01 RegionServer,DataNode, ...