您的位置:首页 > 其它

Scrapy爬虫框架的学习

2017-09-13 18:09 288 查看

第一步安装

首先得安装它,我使用的pip安装的

因为我电脑上面安装了两个python,一个是python2.x,一个是python3.x,所以为了区分,所以,在cmd中,我就使用命令:python2 -m pip install Scrapy (注意我这里使用python2的原因是我给2个python重命名了一下)

安装之后,输入scrapy,出现如下图这样子的信息,表示成功安装了

# -*- coding: utf-8 -*-
import scrapy
from tencentProject.items import TencentprojectItem

class TencentSpider(scrapy.Spider):
# 爬虫名
name = 'tencent'
# 爬虫爬取数据的域范围
allowed_domains = ['tencent.com']
# 1. 需要拼接的url
baseURL = "http://hr.tencent.com/position.php?&start="
# 1. 需要拼接的url地址的偏移量
offset = 0
# 爬虫启动时,读取的url地址列表
start_urls = [baseURL + str(offset)]

# 用来处理response
def parse(self, response):
# 提取每个response的数据
node_list = response.xpath("//tr[@class='even'] | //tr[@class='odd']")

for node in node_list:
# 构建item对象,用来保存数据
item = TencentprojectItem()
# 提取每个职位的信息,并且将提取出的Unicode字符串编码为UTF-8编码
item['positionName'] = node.xpath("./td[1]/a/text()").extract()[0].encode("utf-8")

item['positionLink'] = node.xpath("./td[1]/a/@href").extract()[0].encode("utf-8")

if len(node.xpath("./td[2]/text()")):
item['positionType'] = node.xpath("./td[2]/text()").extract()[0].encode("utf-8")
else:
item['positionType'] = "NULL"

item['peopleNumber'] = node.xpath("./td[3]/text()").extract()[0].encode("utf-8")

item['workLocation'] = node.xpath("./td[4]/text()").extract()[0].encode("utf-8")

item['publishTime'] = node.xpath("./td[5]/text()").extract()[0].encode("utf-8")

# yield 的重要性,是返回数据后还能回来接着执行代码
yield item

# 第一种写法:拼接url,适用场景:页面没有可以点击的请求连接,必须通过拼接url才能获取响应
# if self.offset < 2190:
#     self.offset += 10
#     url = self.baseURL + str(self.offset)
#     yield scrapy.Request(url, callback = self.parse)

# 第二种写法:直接从response获取需要爬取的连接,并发送请求处理,直到链接全部提取完
if len(response.xpath("//a[@class='noactive' and @id='next']")) == 0:

url = response.xpath("//a[@id='next']/@href").extract()[0]
yield scrapy.Request("http://hr.tencent.com/" + url, callback = self.parse)
#def parse_next(self, response):
#    pass


tencent.py
注意:里面的关键字yield 的作用是:返回数据后,还能继续去执行未完成的操作,它不像return,但是,它又有return的返回数据的功能

2、存储

在管道文件pipelines.py 去添加一下代码:

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import json

class TencentprojectPipeline(object):

def __init__(self):
self.f=open("tencent.json","w")
def process_item(self, item, spider):
#设置完后,一定要去去掉settings.py文件中的注释,才能启用管道
'''
ITEM_PIPELINES = {
'tencentProject.pipelines.TencentprojectPipeline': 300,}
'''
content=json.dumps(dict(item),ensure_ascii=False)+",\n"   #json.dumps()转换成json类型的字符串,ensure_ascii=False 表示遵循unicode编码来转换
self.f.write(content)
return item

def close_spider(self,spider):
self.f.close()


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: