我在爬一个有刮痕的网站。parse方法首先提取所有类别链接,然后向parse_category发出一个回调请求。
问题是,如果某个类别有一个产品,它将重定向到“产品”页面。我的parse_category无法识别这个页面。
现在,如何使用产品页解析器解析重定向类别页?
下面是一个例子。
parse找到3个类别页面。http://example.com/products/samsunghttp://example.com/products/dellhttp://example.com/products/apple
pare_category调用所有这些页面。每个返回带有产品列表的html页面。但是apple只有一个产品iMac 27"。因此,它重定向到http://example.com/products/apple/imac_27。这是一个产品page.The类别解析无法解析它。我需要在这个场景中调用产品解析方法parse_product。我该怎么做?
我可以在我的parse_category方法中添加一些逻辑并调用parse_product。我不想要。我要刮擦就行了。但是的,我会给出网址模式或任何其他必要的信息。
这是密码。
class ExampleSpider(BaseSpider):
name = u'example.com'
allowed_domains = [u'www.example.com']
start_urls = [u'http://www.example.com/category.aspx']
def parse(self, response):
hxs = HtmlXPathSelector(response)
anchors = hxs.select('/xpath')
for anchor in anchors:
yield Request(urljoin(get_base_url(response), anchor), callback=self.parse_category)
def parse_category(self, response):
hxs = HtmlXPathSelector(response)
products = hxs.select(products_xpath).extract()
for url in products:
yield Request(url, callback=self.parse_product)
def parse_product(self, response):
# product parsing ...
pass发布于 2013-07-12 11:32:12
您可以选择编写一个实现中间件方法的process_response。每当您的响应是针对产品URL而不是类别时,请为产品解析器创建一个请求对象的副本和更改回调函数。
最后,从中间件返回新的Request对象。注意:您可能需要为新的dont_filter将True设置为Request,以确保DupeFilter不过滤请求。
https://stackoverflow.com/questions/17611695
复制相似问题