本文主要是利用scrapy框架爬取果壳问答中热门问答, 精彩问答的相关信息

环境

win8, python3.7, pycharm

正文

1. 创建scrapy项目文件

在cmd命令行中任意目录下执行以下代码, 即可在该目录下创建GuoKeWenDa项目文件

scrapy startproject GuoKeWenDa

2. 创建爬虫主程序

在cmd中切换到GuoKeWenDa目录下, 执行以下代码:

cd GuoKeWenDa
scrapy genspider GuoKeWenDaSpider GuoKeWenDaSpider.toscrape.com

创建GuoKeWenDaSpider.py文件成功

3. 定义要爬取的项目

分析果壳热门问答果壳精彩问答, 发现两页面的结构一致, 我们爬取其中的主题, 简介, 关注数, 回答数, 标签, 文章链接等6个信息

在items.py中定义

 import scrapy
from scrapy.item import Item, Field class GuokewendaItem(Item):
# define the fields for your item here like:
# name = scrapy.Field()
title = Field()
intro = Field()
attention = Field()
answer = Field()
label = Field()
link = Field() 

4. 编写爬虫主程序

在GuoKeWenDaSpider.py文件中编写:

 import scrapy
from scrapy.spiders import CrawlSpider
from scrapy.selector import Selector
from scrapy.http import Request
from GuoKeWenDa.items import GuokewendaItem class GuoKeWenDa(CrawlSpider):
name = 'GuoKeWenDa'
allowed_domains = ['GuoKeWenDaSpider.toscrape.com']
urls = ['hottest', 'highlight']
#对urls进行遍历
start_urls = ['https://www.guokr.com/ask/{0}/?page={1}'.format(str(m),str(n)) for m in urls for n in range(1, 101)]
def parse(self, response):
item = GuokewendaItem()
#初始化源码
selector = Selector(response)
#用xpath进行解析
infos = selector.xpath('//ul[@class="ask-list-cp"]/li')
for info in infos:
title = info.xpath('div[2]/h2/a/text()').extract()[0].strip()
intro = info.xpath('div[2]/p/text()').extract()[0].strip()
attention = info.xpath('div[1]/p[1]/span/text()').extract()[0]
answer = info.xpath('div[1]/p[2]/span/text()').extract()[0]
labels = info.xpath('div[2]/div/p/a/text()').extract()
link = info.xpath('div[2]/h2/a/@href').extract()[0]
if labels:
label = " ".join(labels) #用join将列表转成以" "分隔的字符串
else:
label =''
item['title'] = title
item['intro'] = intro
item['attention'] = attention
item['answer'] = answer
item['label'] = label
item['link'] = link
yield item

5. 保存到MongoDB

import pymongo

class GuokewendaPipeline(object):
def __init__(self):
'''连接MongoDB'''
client = pymongo.MongoClient(host='localhost')
db = client['test']
guokewenda = db['guokewenda']
self.post= guokewenda
def process_item(self, item, spider):
'''写入MongoDB'''
info = dict(item)
self.post.insert(info)
return item

6. 配置setting

在原有代码中去掉以下代码的注释 (快捷键"Ctrl" + "/")

USER_AGENT = 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
DOWNLOAD_DELAY = 5
DEFAULT_REQUEST_HEADERS = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en',
}
ITEM_PIPELINES = {
'GuoKeWenDa.pipelines.GuokewendaPipeline': 300,
}

7. 新建main.py文件

在GuoKeWenDa文件目录下新建main.py文件, 编辑:

 from scrapy import cmdline
cmdline.execute('scrapy crawl GuoKeWenDa'.split())

执行main.py文件

8. 爬取结果

总结

实际中热门问答只有2页, 因此遍历它的第3到100页就显得太多余:

urls = ['hottest', 'highlight']
start_urls = ['https://www.guokr.com/ask/{0}/?page={1}'.format(str(m),str(n)) for m in urls for n in range(1, 101)]

可利用"+"连接两个url(参考: https://www.jianshu.com/p/9006ddca23b6),  修改为:

start_urls = ['https://www.guokr.com/ask/hottest/?page={}'.format(str(m)) for m in range(1,3)] + ['https://www.guokr.com/ask/highlight/?page={}'.format(n) for n in range(1,101)]

Python项目--Scrapy框架(二)的更多相关文章

  1. Python项目--Scrapy框架(一)

    环境 win8, python3.7, pycharm 正文 1.Scrapy框架的安装 在cmd命令行窗口执行: pip install Scrapy 即可完成Scrapy框架的安装 2. 创建Sc ...

  2. python爬虫scrapy框架——人工识别登录知乎倒立文字验证码和数字英文验证码(2)

    操作环境:python3 在上一文中python爬虫scrapy框架--人工识别知乎登录知乎倒立文字验证码和数字英文验证码(1)我们已经介绍了用Requests库来登录知乎,本文如果看不懂可以先看之前 ...

  3. python爬虫scrapy框架

    Scrapy 框架 关注公众号"轻松学编程"了解更多. 一.简介 Scrapy是用纯Python实现一个为了爬取网站数据.提取结构性数据而编写的应用框架,用途非常广泛. 框架的力量 ...

  4. Python爬虫Scrapy框架入门(1)

    也许是很少接触python的原因,我觉得是Scrapy框架和以往Java框架很不一样:它真的是个框架. 从表层来看,与Java框架引入jar包.配置xml或.property文件不同,Scrapy的模 ...

  5. Python使用Scrapy框架爬取数据存入CSV文件(Python爬虫实战4)

    1. Scrapy框架 Scrapy是python下实现爬虫功能的框架,能够将数据解析.数据处理.数据存储合为一体功能的爬虫框架. 2. Scrapy安装 1. 安装依赖包 yum install g ...

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

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

  7. Python爬虫 ---scrapy框架初探及实战

    目录 Scrapy框架安装 操作环境介绍 安装scrapy框架(linux系统下) 检测安装是否成功 Scrapy框架爬取原理 Scrapy框架的主体结构分为五个部分: 它还有两个可以自定义下载功能的 ...

  8. python的scrapy框架的使用 和xpath的使用 && scrapy中request和response的函数参数 && parse()函数运行机制

    这篇博客主要是讲一下scrapy框架的使用,对于糗事百科爬取数据并未去专门处理 最后爬取的数据保存为json格式 一.先说一下pyharm怎么去看一些函数在源码中的代码实现 按着ctrl然后点击函数就 ...

  9. Python爬虫Scrapy框架入门(2)

    本文是跟着大神博客,尝试从网站上爬一堆东西,一堆你懂得的东西 附上原创链接: http://www.cnblogs.com/qiyeboy/p/5428240.html 基本思路是,查看网页元素,填写 ...

随机推荐

  1. 用git,clone依赖的库

    git clone https://github.com/influxdata/influxdb-java.git cd crfasrnn git submodule update --init -- ...

  2. 关于rtsp的时间戳问题

    这里主要关注的rtp包的时间戳,在rtsp中,播放器的1S钟的定义是和媒体的采样率有关的. 例如视频的采样率是90K,那么最小时间粒度(单位)是1/90000秒,再转换成ms就是 1/90毫秒,这个就 ...

  3. 如何修改MSSQL的用户名

    Alter LOGIN sa DISABLE Alter LOGIN sa WITH NAME = [systemAccount] "systemAccount" 为SA的新名称, ...

  4. Ajax传递json数据简介和一个需要注意的小问题

    Ajax传递json数据 Ajax操作与json数据格式在实际中的运用十分广泛,本文为大家介绍一个两者相结合的小案例: 项目结构 我们新建一个Django项目,在里面创建一个名为app01的应用: p ...

  5. WordPress版微信小程序2.2.0版发布

    2017年8月12日WordPress版微信小程序2.2.0版通过了微信的审核正式发布,此版本的更新以完善功能为主.主要更新的功能是:站内链接,猜你喜欢,热点文章. WordPress版微信小程序开放 ...

  6. js 一些方法

    1.js去除字符串前后的空格 function Trim(str) { return str.replace(/(^\s*)|(\s*$)/g, ""); } 2.js打乱数组的顺 ...

  7. Python中xlrd和xlwt模块使用方法

    本文主要介绍可操作excel文件的xlrd.xlwt模块.其中xlrd模块实现对excel文件内容读取,xlwt模块实现对excel文件的写入. 安装xlrd和xlwt模块 xlrd和xlwt模块不是 ...

  8. 1816647 - Error "Data file of SAP Note is incomplete" uploading a note in SNOTE

    ymptom When uploading an SAP Note in transaction SNOTE you receive the error "Data file of SAP ...

  9. selenium:chromedriver与chrome版本对应关系

    1.chromedriver下载地址:http://npm.taobao.org/mirrors/chromedriver 2.谷歌浏览器与chromedriver的版本对应关系,供参考: Chrom ...

  10. 多线程利器-队列(queue)

    #队列有3中模式,先进先出,先进后出,优先级 1:先进先出import queue q = queue.Queue() #默认是先进先出q.put(12)q.put('jack')q.put({'na ...