1、创建Scrapy项目
首先安scrapy
命令:sudo apt-get install scrapy 或者:pip install scrapy
创建scrapy项目的命令:
scrapy startproject +<项目名字>
示例:scrapy startproject myspider
生成的目录和文件结果如下:
2、创建爬虫
命令:在项目路径下执行:scrapy genspider +<爬虫名字> + <允许爬取的域名>
示例(以腾讯招聘网站为例):
cd myspider
scrapy genspider tencent careers.tencent.com
生成的目录和文件结果如下:
3、完善spider
完善spider即通过方法进行数据的提取等操作
在/myspider/myspider/spiders/tencent.py中修改内容如下:
import scrapy
class TencentSpider(scrapy.Spider):
# 爬虫名字
name = 'tencent'
# 允许爬去范围,防止爬虫爬到别的网站
allowed_domains = ['careers.tencent.com']
# 开始爬取的url地址
start_urls = ['https://careers.tencent.com/search.html?keyword=python']
# 数据提取的方法,接受下载中间件传过来的response
def parse(self, response):
# scrapy的response对象可以直接进行xpath
info = response.xpath('//div[4]/div/a[@class="item-link"]/text()')
print(info)
# 获取具体数据文本的方式如下
# 分组
info_list = response.xpath('//div//a[@class="recruit-list-link"]')
for info in info_list:
# 创建一个数据字典
item = {}
# 利用scrapy封装好的xpath选择器定位元素,并通过extract()或extract_first()来获取结果
item['work_name'] = info.xpath('.//h4/text()').extract_first() # 岗位名称
item['work_duty'] = info.xpath('.//p[@class="recruit-text"]/text()').extract_first() # 岗位职责
print(item)
yield item
注意:
- response.xpath方法的返回结果是一个类似list的类型,其中包含的是selector对象,操作和列表一样,但是有一些额外的方法
- extract() 返回一个包含有字符串的列表
- extract_first() 返回列表中的第一个字符串,列表为空没有返回None
- spider中的parse方法必须有,是spider的一个方法。 被调用时,每个初始URL完成下载后生成的Response 对象将会作为唯一的参数传递给该函数。该方法负责解析返回的数据(response data),提取数据(生成item)以及生成需要进一步处理的URL的 Request 对象
- 需要抓取的url地址必须属于allowed_domains,但是start_urls中的url地址没有这个限制
- 启动爬虫的时候注意启动的位置,是在项目路径下启动
4、利用管道pipeline来处理(保存)数据
4.1 对itcast爬虫进行修改完善
在爬虫parse()函数中最后添加:
yield item
使用yield原因:
- 让整个函数变成一个生成器,有什么好处呢?
- 遍历这个函数的返回值的时候,挨个把数据读到内存,不会造成内存的瞬间占用过高
- python3中的range和python2中的xrange同理
注意:yield能够传递的对象只能是:BaseItem,Request,dict,None
4.2 修改pipelines.py文件
class MyspiderPipeline:
# 爬虫文件中提取数据的方法每yield一次item,就会运行一次
# 该方法为固定名称函数
def process_item(self, item, spider):
print(item)
return item
4.3 在settings.py设置开启pipeline
ITEM_PIPELINES = {
'myspider.pipelines.MyspiderPipeline': 300,
}
4.4 在settings.py设置关闭robots协议
ROBOTSTXT_OBEY = False
4.5 在settings.py设置USER_AGENT
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko'
5、运行scrapy
命令:在项目目录下执行scrapy crawl +<爬虫名字>
示例:scrapy crawl tencent