让我们从逻辑开始:
- 抓取首页-获取所有城市
- 抓取城市页面-获取所有单元网址
- 抓取单元页面-获取所有所需数据
我已经在下面的示例中举例说明了如何实现此目的。我找不到您在示例代码中提到的所有信息,但是希望该代码足够清晰,以使您了解它的作用以及如何添加所需的信息。
import scrapyclass QuotesSpider(scrapy.Spider): name = "quotes" start_urls = [ 'http://www.unitestudents.com/', ] # Step 1 def parse(self, response): for city in response.xpath('//select[@id="frm_homeSelect_city"]/option[not(contains(text(),"Select your city"))]/text()').extract(): # Select all cities listed in the select (exclude the "Select your city" option) yield scrapy.Request(response.urljoin("/"+city), callback=self.parse_citypage) # Step 2 def parse_citypage(self, response): for url in response.xpath('//div[@]/h3/span/a/@href').extract(): #Select for each property the url yield scrapy.Request(response.urljoin(url), callback=self.parse_unitpage) # I could not find any pagination. Otherwise it would go here. # Step 3 def parse_unitpage(self, response): unitTypes = response.xpath('//div[@]/h5/text()').extract() + response.xpath('//h4[@]/text()').extract() for unitType in unitTypes: # There can be multiple unit types so we yield an item for each unit type we can find. yield { 'name': response.xpath('//h1/span/text()').extract_first(), 'type': unitType, # 'price': response.xpath('XPATH GOES HERE'), # Could not find a price on the page # 'distance_beds': response.xpath('XPATH GOES HERE') # Could not find such info }
我认为代码非常干净和简单。注释应阐明为什么我选择使用for循环。如果不清楚,请告诉我,我会尽力解释。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)