scrapy选择器的用法
//selector可以加可以不加
response.selector.xpath("//title/text()").extract_first()
response.selector.css("title::text").extract_first()
response.xpath("//title/text()").extract_first() response.xpath("//div[@id='images']").xpath("//img/@src").extract()[0]
response.css('a::text').re('Name\:(.*)')---需要特殊处理的数据后面可以加re模块
response.xpath("//a/text()").re('Name\:(.*)')--这个后面对象变了,不能再加extract()方法了 spiders的用法
完成爬虫的逻辑url
解析网页数据parse 1.初始start_urls→解析parse→scrapy.Request(url,callback=parse)
item
url继续给下载器 2.name---唯一标识爬虫
3.allowed_domains---允许爬取列表
4.start_urls---从这里开始,可以构造列表,一个一个请求(遍历),get形式的请求
5.custom_settings---字典形式的写法(参考headers设置)可以覆盖项目settings---可以吧请求头写在myspider中
6.crawler---
7.settings---
8.from_crawler----可以拿到全局配置
9.start_requests()----利用改写start_requests()方法,使第一次请求用post请求
def start_requests(self):
yield scrapy.Request(url='http://httpbin.org/post',method='post',callback=self.parse_post) def parse_post(self,response):
print('OK',response.status) 10.make_requests_from_url--改变默认回调函数,将回调函数改写,,如果先写start_requests函数就不会在调用此函数 def make_requests_from_url(self,url):
yield scrapy.Request(url=url,callback=self.parse_index) def parse_index(self,response):
print('OK',response.status) 11.parse默认回调函数--item 可迭代对象,request(加到下载队列) 12.log日志文件--info --debug
self.logger.info(response.status) 13.closed--myspider关闭时调用
item Pipeline的用法
数据清洗
重复检查
存储到数据库
1.process_item---item会自动传给它 2.open_spider---spider开启的时候调用
3.close_spider--spider关闭的时候调用 4.from-crawler----类方法,获取项目中的setting
from scrapy.exceptions import DropItem
标准写法: class PricePipeline(object): vat_factor = 1.15 def process_item(self, item, spider):
if item.get('price'):
if item.get('price_excludes_vat'):
item['price'] = item['price'] * self.vat_factor
return item
else:
raise DropItem("Missing price in %s" % item) 写到json:
import json class JsonWriterPipeline(object): def open_spider(self, spider):
self.file = open('items.jl', 'w') def close_spider(self, spider):
self.file.close() def process_item(self, item, spider):
line = json.dumps(dict(item)) + "\n"
self.file.write(line)
return item 存储到MongoDB:
import pymongo class MongoPipeline(object): collection_name = 'scrapy_items' def __init__(self, mongo_uri, mongo_db):
self.mongo_uri = mongo_uri
self.mongo_db = mongo_db @classmethod
def from_crawler(cls, crawler):
return cls(
mongo_uri=crawler.settings.get('MONGO_URI'),
mongo_db=crawler.settings.get('MONGO_DATABASE', 'items')
) def open_spider(self, spider):
self.client = pymongo.MongoClient(self.mongo_uri)
self.db = self.client[self.mongo_db] def close_spider(self, spider):
self.client.close() def process_item(self, item, spider):
self.db[self.collection_name].insert_one(dict(item))
return item
请求网页,保存图片
import scrapy
import hashlib
from urllib.parse import quote class ScreenshotPipeline(object):
"""Pipeline that uses Splash to render screenshot of
every Scrapy item.""" SPLASH_URL = "http://localhost:8050/render.png?url={}" def process_item(self, item, spider):
encoded_item_url = quote(item["url"])
screenshot_url = self.SPLASH_URL.format(encoded_item_url)
request = scrapy.Request(screenshot_url)
dfd = spider.crawler.engine.download(request, spider)
dfd.addBoth(self.return_item, item)
return dfd def return_item(self, response, item):
if response.status != 200:
# Error happened, return item.
return item # Save screenshot to file, filename will be hash of url.
url = item["url"]
url_hash = hashlib.md5(url.encode("utf8")).hexdigest()
filename = "{}.png".format(url_hash)
with open(filename, "wb") as f:
f.write(response.body) # Store filename in item.
item["screenshot_filename"] = filename
return item
去重操作:
from scrapy.exceptions import DropItem class DuplicatesPipeline(object): def __init__(self):
self.ids_seen = set() def process_item(self, item, spider):
if item['id'] in self.ids_seen:
raise DropItem("Duplicate item found: %s" % item)
else:
self.ids_seen.add(item['id'])
return item
使用item pipeline:
ITEM_PIPELINES = {
'myproject.pipelines.PricePipeline': 300,
'myproject.pipelines.JsonWriterPipeline': 800,
}

  

<scrapy爬虫>基本操作的更多相关文章

  1. 在Pycharm中运行Scrapy爬虫项目的基本操作

    目标在Win7上建立一个Scrapy爬虫项目,以及对其进行基本操作.运行环境:电脑上已经安装了python(环境变量path已经设置好), 以及scrapy模块,IDE为Pycharm .操作如下: ...

  2. 在pycharm中使用scrapy爬虫

    目标在Win7上建立一个Scrapy爬虫项目,以及对其进行基本操作.运行环境:电脑上已经安装了python(环境变量path已经设置好), 以及scrapy模块,IDE为Pycharm .操作如下: ...

  3. scrapy爬虫结果插入mysql数据库

    1.通过工具创建数据库scrapy

  4. Python之Scrapy爬虫框架安装及简单使用

    题记:早已听闻python爬虫框架的大名.近些天学习了下其中的Scrapy爬虫框架,将自己理解的跟大家分享.有表述不当之处,望大神们斧正. 一.初窥Scrapy Scrapy是一个为了爬取网站数据,提 ...

  5. Linux搭建Scrapy爬虫集成开发环境

    安装Python 下载地址:http://www.python.org/, Python 有 Python 2 和 Python 3 两个版本, 语法有些区别,ubuntu上自带了python2.7. ...

  6. Scrapy 爬虫

    Scrapy 爬虫 使用指南 完全教程   scrapy note command 全局命令: startproject :在 project_name 文件夹下创建一个名为 project_name ...

  7. [Python爬虫] scrapy爬虫系列 <一>.安装及入门介绍

    前面介绍了很多Selenium基于自动测试的Python爬虫程序,主要利用它的xpath语句,通过分析网页DOM树结构进行爬取内容,同时可以结合Phantomjs模拟浏览器进行鼠标或键盘操作.但是,更 ...

  8. 同时运行多个scrapy爬虫的几种方法(自定义scrapy项目命令)

    试想一下,前面做的实验和例子都只有一个spider.然而,现实的开发的爬虫肯定不止一个.既然这样,那么就会有如下几个问题:1.在同一个项目中怎么创建多个爬虫的呢?2.多个爬虫的时候是怎么将他们运行起来 ...

  9. 如何让你的scrapy爬虫不再被ban之二(利用第三方平台crawlera做scrapy爬虫防屏蔽)

    我们在做scrapy爬虫的时候,爬虫经常被ban是常态.然而前面的文章如何让你的scrapy爬虫不再被ban,介绍了scrapy爬虫防屏蔽的各种策略组合.前面采用的是禁用cookies.动态设置use ...

随机推荐

  1. leetcood学习笔记-58-最后一个单词的长度

    题目描述: 第一次解答: class Solution: def lengthOfLastWord(self, s: str) -> int: L=s.strip().split(" ...

  2. 判断访问浏览器客户端类型(pc,mac,ipad,iphone,android)

    <script type="text/javascript"> //平台.设备和操作系统 var system = { win: false, mac: false, ...

  3. SCOI 2014 new :未来展望

    后期计划(可能延续到noip) 后期计划这种东西..唉...经历了三周的停课生涯,我似乎已经找到了一种状态,就是我一直期盼的状态,然后为了不落泪退役,具体是这样的: 由于现在的学习任务不太紧张了,所以 ...

  4. 执行SQL语句---SELECT

    1.通常从MySQL数据库中检索数据有4个步骤: (1)发出查询: 用mysql_query发出查询. (2)检索数据: 用mysql_store_result/mysql_use_result (3 ...

  5. O(n)线性时间求解第k大-HDU6040-CSU2078

    目录 目录 思路 (有任何问题欢迎留言或私聊 && 欢迎交流讨论哦 目录 HDU6040:传送门  \(m(m\leq 100)\)次查询长度为\(n(n \leq 1e7)\)区间的 ...

  6. PostgreSQL/GREENPLUM关联更新

    update a_t AA set /*AA.*/ sqlstr = 'qqq' from a_t BB where aa.id <> BB.id and aa.name = BB.nam ...

  7. Delphi中文件名函数-路径、名称、子目录、驱动器、扩展名

    文件名函数 文件名函数可以对文件的名称.所在子目录.驱动器和扩展名等进行操作.下表列出这些函数及其功能. 函数说明 ExpandFileName() //返回文件的全路径(含驱动器.路径) Extra ...

  8. L1正则化可以解决过拟合问题(稀疏解)

    损失函数最小,也就是求极值点,也就是损失函数导数为0.上面也说了,如果d0+λ和d0-λ为异号的时候刚好为极值点,损失函数导数为0(w为0是条件).而对于L2正则化,在w=0时并不一定是极值点而是d0 ...

  9. 5步减小你的CSS样式表

    第一步:学会如何组合选择器 什么是选择器?如果你还不知道什么叫做”选择器”,你可以先参考一下w3schools.com的CSS语法概述. 未优化的CSS代码在下面的图例中,你会看到来自三个不同选择器的 ...

  10. java——有1、2、3、4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?

    package java_day10; /* * 有1.2.3.4个数字,能组成多少个互不相同且无重复数字的三位数?都是多少? */ public class Demo04 { public stat ...