Scrapy-following-links
提供:Dev Guides
スクレイピー-リンクをたどる
説明
この章では、関心のあるページのリンクを抽出し、それらを追跡し、そのページからデータを抽出する方法を学習します。 このため、リンクに次の変更を加える必要があります:/scrapy/scrapy_using_item [前のコード]次のように表示-
import scrapy
from tutorial.items import DmozItem
class MyprojectSpider(scrapy.Spider):
name = "project"
allowed_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/",
]
def parse(self, response):
for href in response.css("ul.directory.dir-col > li > a::attr('href')"):
url = response.urljoin(href.extract())
yield scrapy.Request(url, callback = self.parse_dir_contents)
def parse_dir_contents(self, response):
for sel in response.xpath('//ul/li'):
item = DmozItem()
item['title'] = sel.xpath('a/text()').extract()
item['link'] = sel.xpath('a/@href').extract()
item['desc'] = sel.xpath('text()').extract()
yield item
上記のコードには、次のメソッドが含まれています-
- * parse()*-関心のあるリンクを抽出します。
- response.urljoin -parse()メソッドはこのメソッドを使用して新しいURLを作成し、後でコールバックに送信される新しいリクエストを提供します。
- * parse_dir_contents()*-これは実際に対象のデータをスクレイプするコールバックです。
ここで、Scrapyはコールバックメカニズムを使用してリンクをたどります。 このメカニズムを使用すると、より大きなクローラーを設計し、関心のあるリンクをたどって、さまざまなページから目的のデータを取得できます。 通常のメソッドはコールバックメソッドになり、アイテムを抽出し、次のページに続くリンクを探し、同じコールバックのリクエストを提供します。
次の例は、次のページへのリンクをたどるループを生成します。
def parse_articles_follow_next_page(self, response):
for article in response.xpath("//article"):
item = ArticleItem()
... extract article data here
yield item
next_page = response.css("ul.navigation > li.next-page > a::attr('href')")
if next_page:
url = response.urljoin(next_page[0].extract())
yield scrapy.Request(url, self.parse_articles_follow_next_page)