デフォルトでは、元の開始URLにアクセスすることはできません。
ただし、make_requests_from_url
メソッドをオーバーライドして、開始URLをmeta
に入れることができます。次に、パースでそこから抽出することができます(その解析メソッドの後続のリクエストで、その開始URLを転送することを忘れないでください)。
私はCrawlSpider
で働いていないと、多分何マキシムが示唆することはあなたのために働くが、response.url
が可能リダイレクト後の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の「Go to definition」機能を使って、治療ソースを確認し、Request
、make_requests_from_url
などのクラスとメソッドが期待するパラメータを理解することができます。コードを手に入れておくと時間が節約できますが、最初は難しいように見えるかもしれません。
weblinksテーブルと同じテーブルのstart_urlフィールドを使用できますか(使用しているDjangoItemの場合のように)?確かに、それは冗長な非正規化を作成しますが、明示的に呼び出すことを避けたい場合は、これが役に立ちます。 – zubinmehta