我有一个spider,它在spidering的开头以一个小列表allowed_domains
开头。我需要在解析器中动态地向这个白名单中添加更多的域,因为后续的请求仍在被过滤,所以下面的代码并没有完成。解析器中是否还有另一个更新allowed_domains
?在
class APSpider(BaseSpider):
name = "APSpider"
allowed_domains = ["www.somedomain.com"]
start_urls = [
"http://www.somedomain.com/list-of-websites",
]
...
def parse(self, response):
soup = BeautifulSoup( response.body )
for link_tag in soup.findAll('td',{'class':'half-width'}):
_website = link_tag.find('a')['href']
u = urlparse.urlparse(_website)
self.allowed_domains.append(u.netloc)
yield Request(url=_website, callback=self.parse_secondary_site)
...
(在写这个答案的时候,
scrapy
的最新版本是1.0.3
。此答案适用于scrapy
)的所有最新版本由于
OffsiteMiddleware
只在处理spider_opened
信号时初始化预编译的regex对象时才读取allowed_domains
中的内容,allowed_domains
中的值以后永远不会被访问。因此,仅仅更新
allowed_domains
的内容并不能解决问题。在基本上需要两个步骤:
allowed_domains
的内容。在OffsiteMiddleware
中的regex缓存。在以下是我在步骤2中使用的代码:
上面的代码应该在响应回调中调用,因此
self
这里应该是spider类的一个实例。在另请参见:
您可以尝试以下方法:
相关问题 更多 >
编程相关推荐