Scrapy-スパイダー
説明
Spiderは、Webサイトを介してリンクをたどり、ページから情報を抽出する方法を定義するクラスです。
Scrapyのデフォルトのスパイダーは次のとおりです-
スクレイピースパイダー
それは他のすべてのクモが継承しなければならないクモです。次のクラスがあります-
class scrapy.spiders.Spider次の表は、scrapy.Spiderクラスのフィールドを示しています。
| シニア番号 | フィールドと説明 | 
|---|---|
| 1 | name それはあなたのクモの名前です。 | 
| 2 | allowed_domains これは、スパイダーがクロールするドメインのリストです。 | 
| 3 | start_urls これはURLのリストであり、スパイダーがクロールを開始する後のクロールのルートになります。 | 
| 4 | custom_settings これらの設定は、スパイダーを実行すると、プロジェクト全体の構成から上書きされます。 | 
| 5 | crawler これは、スパイダーインスタンスがバインドされているCrawlerオブジェクトにリンクする属性です。 | 
| 6 | settings これらは、スパイダーを実行するための設定です。 | 
| 7 | logger これは、ログメッセージの送信に使用されるPythonロガーです。 | 
| 8 | from_crawler(crawler,*args,**kwargs) これは、スパイダーを作成するクラスメソッドです。パラメータは次のとおりです。 
 | 
| 9 | start_requests() 特定のURLが指定されておらず、スパイダーがスクラップのために開かれている場合、Scrapyはstart_requests()メソッドを呼び出します。 | 
| 10 | make_requests_from_url(url) これは、URLをリクエストに変換するために使用されるメソッドです。 | 
| 11 | parse(response) このメソッドは応答を処理し、より多くのURLに続いて廃棄されたデータを返します。 | 
| 12 | log(message[,level,component]) スパイダーロガーを介してログメッセージを送信する方法です。 | 
| 13 | closed(reason) このメソッドは、スパイダーが閉じたときに呼び出されます。 | 
蜘蛛の議論
スパイダー引数は開始URLを指定するために使用され、crawlコマンドを使用して渡されます。 -a オプション、次のように表示-
scrapy crawl first_scrapy -a group = accessories次のコードは、スパイダーが引数を受け取る方法を示しています-
import scrapy 
class FirstSpider(scrapy.Spider): 
   name = "first" 
   
   def __init__(self, group = None, *args, **kwargs): 
      super(FirstSpider, self).__init__(*args, **kwargs) 
      self.start_urls = ["http://www.example.com/group/%s" % group]ジェネリックスパイダー
一般的なスパイダーを使用して、スパイダーをサブクラス化できます。彼らの目的は、特定のルールに基づいてWebサイト上のすべてのリンクをたどり、すべてのページからデータを抽出することです。
次のスパイダーで使用されている例では、次のフィールドを持つプロジェクトがあると仮定します-
import scrapy 
from scrapy.item import Item, Field 
  
class First_scrapyItem(scrapy.Item): 
   product_title = Field() 
   product_link = Field() 
   product_description = Field()CrawlSpider
CrawlSpiderは、リンクをたどり、複数のページを廃棄するための一連のルールを定義します。次のクラスがあります-
class scrapy.spiders.CrawlSpider以下はCrawlSpiderクラスの属性です-
ルール
これは、クローラーがリンクをたどる方法を定義するルールオブジェクトのリストです。
次の表は、CrawlSpiderクラスのルールを示しています-
| シニア番号 | ルールと説明 | 
|---|---|
| 1 | LinkExtractor スパイダーがリンクをたどり、データを抽出する方法を指定します。 | 
| 2 | callback 各ページがスクレイピングされた後に呼び出されます。 | 
| 3 | follow リンクをたどり続けるかどうかを指定します。 | 
parse_start_url(response)
初期応答の解析を許可することにより、アイテムまたは要求オブジェクトのいずれかを返します。
Note −解析関数は、CrawlSpiderがそのロジックを実装するために使用するため、ルールの記述中に解析以外の解析関数の名前を変更してください。
次の例を見てみましょう。ここでは、スパイダーがdemoexample.comのホームページのクロールを開始し、すべてのページ、リンクを収集し、parse_itemsメソッドを使用して解析します-
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
class DemoSpider(CrawlSpider):
   name = "demo"
   allowed_domains = ["www.demoexample.com"]
   start_urls = ["http://www.demoexample.com"]
      
   rules = ( 
      Rule(LinkExtractor(allow =(), restrict_xpaths = ("//div[@class = 'next']",)),
         callback = "parse_item", follow = True),
   )
   
   def parse_item(self, response):
      item = DemoItem()
      item["product_title"] = response.xpath("a/text()").extract()
      item["product_link"] = response.xpath("a/@href").extract()
      item["product_description"] = response.xpath("div[@class = 'desc']/text()").extract()
      return itemsXMLFeedSpider
これは、XMLフィードからスクレイプし、ノードを反復処理するスパイダーの基本クラスです。次のクラスがあります-
class scrapy.spiders.XMLFeedSpider次の表は、イテレータとタグ名を設定するために使用されるクラス属性を示しています-
| シニア番号 | 属性と説明 | 
|---|---|
| 1 | iterator 使用するイテレータを定義します。iternodes、html、またはxmlのいずれかです。デフォルトはiternodesです。 | 
| 2 | itertag 繰り返すノード名の文字列です。 | 
| 3 | namespaces これは、register_namespace()メソッドを使用して名前空間を自動的に登録する(prefix、uri)タプルのリストによって定義されます。 | 
| 4 | adapt_response(response) 応答を受信し、スパイダーミドルウェアから到着するとすぐに、スパイダーが解析を開始する前に応答本体を変更します。 | 
| 5 | parse_node(response,selector) 指定されたタグ名に一致するノードごとに呼び出されると、応答とセレクターを受け取ります。 Note −このメソッドをオーバーライドしないと、スパイダーは機能しません。 | 
| 6 | process_results(response,results) スパイダーから返された結果と応答のリストを返します。 | 
CSVFeedSpider
各行を反復処理し、応答としてCSVファイルを受信し、parse_row()メソッドを呼び出します。次のクラスがあります-
class scrapy.spiders.CSVFeedSpider次の表に、CSVファイルに関して設定できるオプションを示します。
| シニア番号 | オプションと説明 | 
|---|---|
| 1 | delimiter これは、各フィールドのコンマ( '、')区切り文字を含む文字列です。 | 
| 2 | quotechar これは、各フィールドの引用符( '"')を含む文字列です。 | 
| 3 | headers これは、フィールドを抽出できるステートメントのリストです。 | 
| 4 | parse_row(response,row) 応答と各行をヘッダーのキーとともに受信します。 | 
CSVFeedSpiderの例
from scrapy.spiders import CSVFeedSpider
from demoproject.items import DemoItem  
class DemoSpider(CSVFeedSpider): 
   name = "demo" 
   allowed_domains = ["www.demoexample.com"] 
   start_urls = ["http://www.demoexample.com/feed.csv"] 
   delimiter = ";" 
   quotechar = "'" 
   headers = ["product_title", "product_link", "product_description"]  
   
   def parse_row(self, response, row): 
      self.logger.info("This is row: %r", row)  
      item = DemoItem() 
      item["product_title"] = row["product_title"] 
      item["product_link"] = row["product_link"] 
      item["product_description"] = row["product_description"] 
      return itemSitemapSpider
Sitemapsの助けを借りたSitemapSpiderは、robots.txtからURLを見つけてWebサイトをクロールします。次のクラスがあります-
class scrapy.spiders.SitemapSpider次の表は、SitemapSpider −のフィールドを示しています。
| シニア番号 | フィールドと説明 | 
|---|---|
| 1 | sitemap_urls サイトマップをポイントしてクロールするURLのリスト。 | 
| 2 | sitemap_rules これはタプル(regex、callback)のリストであり、regexは正規表現であり、callbackは正規表現に一致するURLを処理するために使用されます。 | 
| 3 | sitemap_follow これは、従うべきサイトマップの正規表現のリストです。 | 
| 4 | sitemap_alternate_links 単一のURLに対してたどる代替リンクを指定します。 | 
SitemapSpiderの例
次のSitemapSpiderはすべてのURLを処理します-
from scrapy.spiders import SitemapSpider  
class DemoSpider(SitemapSpider): 
   urls = ["http://www.demoexample.com/sitemap.xml"]  
   
   def parse(self, response): 
      # You can scrap items here次のSitemapSpiderは、コールバックを使用していくつかのURLを処理します-
from scrapy.spiders import SitemapSpider  
class DemoSpider(SitemapSpider): 
   urls = ["http://www.demoexample.com/sitemap.xml"] 
   
   rules = [ 
      ("/item/", "parse_item"), 
      ("/group/", "parse_group"), 
   ]  
   
   def parse_item(self, response): 
      # you can scrap item here  
   
   def parse_group(self, response): 
      # you can scrap group here次のコードは、URLが含まれているrobots.txtのサイトマップを示しています /sitemap_company −
from scrapy.spiders import SitemapSpider
class DemoSpider(SitemapSpider): 
   urls = ["http://www.demoexample.com/robots.txt"] 
   rules = [ 
      ("/company/", "parse_company"), 
   ] 
   sitemap_follow = ["/sitemap_company"]  
   
   def parse_company(self, response): 
      # you can scrap company here次のコマンドに示すように、SitemapSpiderを他のURLと組み合わせることもできます。
from scrapy.spiders import SitemapSpider  
class DemoSpider(SitemapSpider): 
   urls = ["http://www.demoexample.com/robots.txt"] 
   rules = [ 
      ("/company/", "parse_company"), 
   ]  
   
   other_urls = ["http://www.demoexample.com/contact-us"] 
   def start_requests(self): 
      requests = list(super(DemoSpider, self).start_requests()) 
      requests += [scrapy.Request(x, self.parse_other) for x in self.other_urls] 
      return requests 
   def parse_company(self, response): 
      # you can scrap company here... 
   def parse_other(self, response): 
      # you can scrap other here...