デフォルトでは、元の開始URLにアクセスできません。
ただし、メソッドをオーバーライドmake_requests_from_url
して、開始URLをに入れることができますmeta
。次に、解析でそこから抽出できます(その解析メソッドで後続のリクエストを生成する場合は、その開始URLを転送することを忘れないでください)。
私はこれまで作業したことがなく、マキシムが提案するものがあなたのために機能するかもしれませんが、可能なリダイレクトの後にURLがあるCrawlSpider
ことを覚えておいてください。response.url
これは私がそれを行う方法の例ですが、これは単なる例であり(scrapyチュートリアルから取得)、テストされていません:
class MySpider(CrawlSpider):
name = 'example.com'
allowed_domains = ['example.com']
start_urls = ['http://www.example.com']
rules = (
# Extract links matching 'category.php' (but not matching 'subsection.php')
# and follow links from them (since no callback means follow=True by default).
Rule(SgmlLinkExtractor(allow=('category\.php', ), deny=('subsection\.php', ))),
# Extract links matching 'item.php' and parse them with the spider's method parse_item
Rule(SgmlLinkExtractor(allow=('item\.php', )), callback='parse_item'),
)
def parse(self, response): # When writing crawl spider rules, avoid using parse as callback, since the CrawlSpider uses the parse method itself to implement its logic. So if you override the parse method, the crawl spider will no longer work.
for request_or_item in CrawlSpider.parse(self, response):
if isinstance(request_or_item, Request):
request_or_item = request_or_item.replace(meta = {'start_url': response.meta['start_url']})
yield request_or_item
def make_requests_from_url(self, url):
"""A method that receives a URL and returns a Request object (or a list of Request objects) to scrape.
This method is used to construct the initial requests in the start_requests() method,
and is typically used to convert urls to requests.
"""
return Request(url, dont_filter=True, meta = {'start_url': url})
def parse_item(self, response):
self.log('Hi, this is an item page! %s' % response.url)
hxs = HtmlXPathSelector(response)
item = Item()
item['id'] = hxs.select('//td[@id="item_id"]/text()').re(r'ID: (\d+)')
item['name'] = hxs.select('//td[@id="item_name"]/text()').extract()
item['description'] = hxs.select('//td[@id="item_description"]/text()').extract()
item['start_url'] = response.meta['start_url']
return item
ご不明な点がございましたら、お問い合わせください。ところで、PyDevの「定義に移動」機能を使用すると、スクレイプなソースを確認し、どのパラメーターRequest
、make_requests_from_url
および他のクラスとメソッドが期待するかを理解できます。最初は難しいように思われるかもしれませんが、コードに入ると時間を節約できます。