我是 scrapy 的新手,我一直在尝试抓取 http://www.icbse.com/schools/state/maharashtra ,但我遇到了问题。 在显示为可用的学校链接总数中,该页面一次只显示 50 个,并且是无序的。
但是,如果重新加载页面,它会显示 50 个新的学校链接列表。其中一些与刷新前的第一个链接不同,而另一些则保持不变。
我想做的是将链接添加到 Set(),一旦 len(set) 达到学校总数的长度,我想将该 Set 发送到解析函数。 我不明白关于解决这个问题的两件事。
- 在哪里定义一个
set来保留链接并且不会在每次调用 parse() 时都刷新。 - 如何在 scrapy 中重新加载页面。
这是我当前的代码:
import scrapy
import re
from icbse.items import IcbseItem
class IcbseSpider(scrapy.Spider):
name = "icbse"
allowed_domains = ["www.icbse.com"]
start_urls = [
"http://www.icbse.com/schools/",
]
def parse(self, response):
for i in xrange(20): # I thought if i iterate the start URL,
# I could probably have the page reload.
# It didn't work though.
for href in response.xpath(
'//div[@class="row"]/div[3]//span[@class="list-group-item"]\
/a/@href').extract():
url = response.urljoin(href)
yield scrapy.Request(url, callback=self.parse_dir_contents)
def parse_dir_contents(self, response):
# total number of schools found on page
pages = response.xpath(
"//div[@class='container']/strong/text()").extract()[0]
self.captured_schools_set = set() # Placing the Set here doesn't work!
while len(self.captured_schools_set) != int(pages):
yield scrapy.Request(response.url, callback=self.reload_url)
for school in self.captured_schools_set:
yield scrapy.Request(school, callback=self.scrape_school_info)
def reload_url(self, response):
for school_href in response.xpath(
"//h4[@class='school_name']/a/@href").extract():
self.captured_schools_set.add(response.urljoin(school_href))
def scrape_school_info(self, response):
item = IcbseItem()
try:
item["School_Name"] = response.xpath(
'//td[@class="tfield"]/strong/text()').extract()[0]
except:
item["School_Name"] = ''
pass
try:
item["streetAddress"] = response.xpath(
'//td[@class="tfield"]')[1].xpath(
"//span[@itemprop='streetAddress']/text()").extract()[0]
except:
item["streetAddress"] = ''
pass
yield item
请您参考如下方法:
您正在迭代一个空集:
self.captured_schools_set = set() # Placing the Set here doesn't work!
while len(self.captured_schools_set) != int(pages):
yield scrapy.Request(response.url, callback=self.reload_url)
for school in self.captured_schools_set:
yield scrapy.Request(school, callback=self.scrape_school_info)
因此,学校的请求永远不会被触发。
你应该重新加载,开火 http://www.icbse.com/schools/带有 dont_filter=True 属性的请求,因为在默认设置中,scrapy 会过滤掉重复项。
但看起来你并没有开火http://www.icbse.com/schools/请求,但是 ( http://www.icbse.com/schools/state/andaman-nicobar ) "/state/name"请求;在上面的第 4 行中你正在触发 request.url,这是一个问题,更改为/schools/
