Python项目--Scrapy框架(二)
本文主要是利用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框架(二)的更多相关文章
- Python项目--Scrapy框架(一)
环境 win8, python3.7, pycharm 正文 1.Scrapy框架的安装 在cmd命令行窗口执行: pip install Scrapy 即可完成Scrapy框架的安装 2. 创建Sc ...
- python爬虫scrapy框架——人工识别登录知乎倒立文字验证码和数字英文验证码(2)
操作环境:python3 在上一文中python爬虫scrapy框架--人工识别知乎登录知乎倒立文字验证码和数字英文验证码(1)我们已经介绍了用Requests库来登录知乎,本文如果看不懂可以先看之前 ...
- python爬虫scrapy框架
Scrapy 框架 关注公众号"轻松学编程"了解更多. 一.简介 Scrapy是用纯Python实现一个为了爬取网站数据.提取结构性数据而编写的应用框架,用途非常广泛. 框架的力量 ...
- Python爬虫Scrapy框架入门(1)
也许是很少接触python的原因,我觉得是Scrapy框架和以往Java框架很不一样:它真的是个框架. 从表层来看,与Java框架引入jar包.配置xml或.property文件不同,Scrapy的模 ...
- Python使用Scrapy框架爬取数据存入CSV文件(Python爬虫实战4)
1. Scrapy框架 Scrapy是python下实现爬虫功能的框架,能够将数据解析.数据处理.数据存储合为一体功能的爬虫框架. 2. Scrapy安装 1. 安装依赖包 yum install g ...
- 爬虫(十五):Scrapy框架(二) Selector、Spider、Downloader Middleware
1. Scrapy框架 1.1 Selector的用法 我们之前介绍了利用Beautiful Soup.正则表达式来提取网页数据,这确实非常方便.而Scrapy还提供了自己的数据提取方法,即Selec ...
- Python爬虫 ---scrapy框架初探及实战
目录 Scrapy框架安装 操作环境介绍 安装scrapy框架(linux系统下) 检测安装是否成功 Scrapy框架爬取原理 Scrapy框架的主体结构分为五个部分: 它还有两个可以自定义下载功能的 ...
- python的scrapy框架的使用 和xpath的使用 && scrapy中request和response的函数参数 && parse()函数运行机制
这篇博客主要是讲一下scrapy框架的使用,对于糗事百科爬取数据并未去专门处理 最后爬取的数据保存为json格式 一.先说一下pyharm怎么去看一些函数在源码中的代码实现 按着ctrl然后点击函数就 ...
- Python爬虫Scrapy框架入门(2)
本文是跟着大神博客,尝试从网站上爬一堆东西,一堆你懂得的东西 附上原创链接: http://www.cnblogs.com/qiyeboy/p/5428240.html 基本思路是,查看网页元素,填写 ...
随机推荐
- 定时重启tomcat
写个简单的定时重启,弄了一上午,主要是crontab里面奇怪 #!/bin/bash p=`ps -ef |grep tomcat |head -n 1|awk -F" " '{p ...
- PPTV(pplive)_forap_1084_9993.exe 木马清除经历
## 流氓行经 这几天电脑上突然自动安装pptv,金山毒霸清除了也不管用, 卸载了pptv过一会又自动安装上了,太嚣张了哈. ## 监控进程跟目录变化 接下来使用 ProcessMonitor 监控进 ...
- Git 2.x 中git push时遇到 push.default 警告的解决方法
近在学习使用 git&GitHub,然后今天遇到了一个问题.在执行 git add 和 git commit 操作之后,再进行 git push 操作,出现了如下提示: $ git push ...
- Linux环境安装PostgreSQL-10.1
转载自:https://www.cnblogs.com/LinBug/p/8082790.html Linux环境安装PostgreSQL-10.1 环境及资源 Linux版本:CentOS re ...
- 阿里云centos5升级yum源为6
升级后出现Errno -3] Error performing checksum 需要安装 python-hashlib Python 2.4 安装 hashlib 2012年11月13日 14:29 ...
- hbase hbck命令
hbase hbck 只做检查 hbase hbck -fixMeta 根据region目录中的.regioninfo,生成meta表` hbase hbck -fixAssignments 把met ...
- 廖雪峰Java7处理日期和时间-3java.time的API-2ZonedDateTime
ZonedDatetime = LocalDateTime + ZoneId ZonedDateTime:带时区的日期和时间 ZoneId:新的API定义的时区对象(取代几句的java.util.Ti ...
- Git和代码规范
最近发现和代码有点问题,总是在上线的紧急关头,和代码浪费了很多的时间,那么总结一下和代码的规范吧. 1.首先我们从master拉取代码进行开发. 2.开发完成之后,把代码上到test上面进行测试,上t ...
- 使用 tag 文件定义自定义标签
----------------------------------------------------------------------- 在jsp文件中,可以引用tag和tld文件. 1.对于t ...
- background-size的应用情景:当给出的背景图片大于实际网页需要布局的图片大小时
网页需求是:50*50 如果只设置 width:50px;height:50px;background-image("images/XXX.png"); 效果如下: 添加设置:b ...