【ScrapyFramework】「バージョン2.4.0ソースコード」項目(項目)詳細章

すべてのソースコード分析記事インデックスディレクトリポータル

[Scrapy Framework]バージョン2.4.0ソースコード:すべての構成ディレクトリインデックス

前書き

データスクレイピングの主な目的は、非構造化ソース(通常はWebページ)から構造化データを抽出することです。

この章では、ソースコードの事例を紹介します。個人的には、データ処理の操作が面倒で、データ処理プロセスが最も単純なコンテンツに簡略化されていると感じています。列のクローラーの例では、記事は面倒で、友達は飛び越えることができます。例を見てください。

アイテムは、使用するために読み取り、書き込み、および変更できるデータの辞書を提供します。

辞書:データ型は辞書です。

アイテムオブジェクト:辞書と同じ操作ができます。

from scrapy.item import Item, Field

class CustomItem(Item):
    one_field = Field()
    another_field = Field()

データクラスオブジェクト:プロジェクトデータのデータ型を定義するためのシリアル化をサポート

from dataclasses import dataclass

@dataclass
class CustomItem:
    one_field: str
    another_field: int

attrsオブジェクト:シリアル化変換番号属性をサポート

import attr

@attr.s
class CustomItem:
    one_field = attr.ib(str)
    another_field = attr.ib(convert=float)

アイテムを使用する

フィールドを宣言する

アイテムサブクラスは、単純なクラス定義構文とフィールド属性を使用します。つまり、キャプチャされたコンテンツのリストフィールド名をカスタマイズし、分割表の形式でキャプチャされたデータをテーブルに入力します。

import scrapy

class Product(scrapy.Item):
    name = scrapy.Field()
    price = scrapy.Field()
    stock = scrapy.Field()
    tags = scrapy.Field()
    last_updated = scrapy.Field(serializer=str)

フィールドデータ

  1. アイテムを作成する
>>> product = Product(name='Desktop PC', price=1000)
>>> print(product)
Product(name='Desktop PC', price=1000)
  1. アイテムの価値を得る
>>> product['name']
Desktop PC
>>> product.get('name')
Desktop PC
>>> product['price']
1000
# 一般错误提示,同字典报错
>>> product['lala'] # 获取未定义的字段值
Traceback (most recent call last):
    ...
KeyError: 'lala'
  1. アイテムの値を設定します
>>> product['last_updated'] = 'today'
>>> product['last_updated']
today
  1. 辞書操作項目
>>> product.keys()
['price', 'name']

>>> product.items()
[('price', 1000), ('name', 'Desktop PC')]
  1. アイテムをコピーする
product2 = product.copy()
# 或者
product2 = Product(product)
  1. 辞書作成項目
>>> Product({
    
    'name': 'Laptop PC', 'price': 1500})
Product(price=1500, name='Laptop PC')
  1. データ型の拡張
# 直接定义数据类型
class DiscountedProduct(Product):
    discount_percent = scrapy.Field(serializer=str)
    discount_expiration_date = scrapy.Field()

# 使用序列化的方式进行定义
class SpecificProduct(Product):
    name = scrapy.Field(Product.fields['name'], serializer=my_serializer)

スパイダーでの使用

from myproject.items import Product
 
def parse(self, response):
	item = Product()
    item["name"]= response.xpath('//div[@class="xxx"]/text()').extract()
	item["price"]= response.xpath('//div[@class="xxx"]/text()').extract()
	item["stock"]= response.xpath('//div[@class="xxx"]/text()').extract()
	item["tags"]= response.xpath('//div[@class="xxx"]/text()').extract()
	item["last_updated"]= response.xpath('//div[@class="xxx"]/text()').extract()
    yield item 

おすすめ

転載: blog.csdn.net/qq_20288327/article/details/113491113