python爬虫Scrapy框架

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设置对应的配置信息。

  1. 在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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值