Scrapy框架
是一个Python爬虫框架,适合做一些大型爬虫项目。
Scrapy框架常见命令:
1、基本格式:scrapy 命令名 -参数(如scrapy fetch –h显示fetch命令帮助,fetch显示爬虫爬取过程)
2、Shell命令,启动Scrapy交互终端 >scrapy shell http://www.baidu.com --nolog
3、Startproject命令 创建爬虫项目: scrapy startproject first(爬虫项目名)
4、Version命令 scrapy version
5、View命令 下载某个网页,并且用浏览器查看 scrapy view http://news.163.com
6、bench命令测试本地性能
7、scrapy genspider -l 展示爬虫模板
8、scrapy genspider –t basic csc baidu.com 基于basic模板创建csc爬取百度
9、Scrapy check csc(爬虫名)命令用于测试
10、scrapy crawl csc命令用于启动某个爬虫文件
11、scrapy list展示当前项目下,可用的爬虫名
12、scrapy edit csc用于打开编辑器编辑爬虫(这个命令只能用于linux系统)
13、scrapy parse http://www.baidu.com获取指定url网址,并行分析处理
Xpath表达式:运行效率比正则表达式快
/表示从顶端开始寻找标签(如/html表示从html顶端开始寻找,/html/head提取html下的head这个标签里面所有的内容)。
/html/head/title/text()提取网页的标题内容。
Text()提取文本信息
@提取标签里面的属性信息
//寻找当前页所有的标签 //li[@属性=。。](//li[@class=’hidden-xs’]/a@href)
第一个scrapy爬虫:
思路:首先编辑爬虫项目里面的items.py,设置爬取的目标,pipelines设置后续的处理,settings设置对应的配置信息。
- 在cmd中进入爬虫项目文件夹,运行命令scrapy genspider –t basic csc baidu.com
基于basic模板创建csc爬取百度
2、用pycharm打开项目文件,编辑items.py文件
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class FirstItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
content = scrapy.Field()#创建容器
link = scrapy.Field()
3、进入pipelines.py设置后续处理
class FirstPipeline(object):
def process_item(self, item, spider):
print(item['content'])#处理方式
return item
4、进入settings文件,进行设置,找到pipelines,取消注释
ITEM_PIPELINES = {
'first.pipelines.FirstPipeline': 300,
}
5、将robots.txt rules爬虫规则,设置围殴不遵守
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
6、最后编辑爬虫文件
import scrapy
from first.items import FirstItem
class CscSpider(scrapy.Spider):
name = 'csc'
allowed_domains = ['baidu.com']
start_urls = ['http://www.baidu.com/']
def parse(self, response):
item = FirstItem()
item['content']=response.xpath('/html/head/title/text()').extract()
yield item