动态添加到Scrapy spid中允许的\u域

2024-10-03 04:25:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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)

...

Tags: selfcom解析器parseresponsetagwwwlink
2条回答

(在写这个答案的时候,scrapy的最新版本是1.0.3。此答案适用于scrapy)的所有最新版本

由于OffsiteMiddleware只在处理spider_opened信号时初始化预编译的regex对象时才读取allowed_domains中的内容,allowed_domains中的值以后永远不会被访问。
因此,仅仅更新allowed_domains的内容并不能解决问题。在

基本上需要两个步骤:

  1. 根据您的实际需要更新allowed_domains的内容。在
  2. 刷新OffsiteMiddleware中的regex缓存。在

以下是我在步骤2中使用的代码:

# Refresh the regex cache for `allowed_domains`
for mw in self.crawler.engine.scraper.spidermw.middlewares:
    if isinstance(mw, scrapy.spidermiddlewares.offsite.OffsiteMiddleware):
        mw.spider_opened(self)

上面的代码应该在响应回调中调用,因此self这里应该是spider类的一个实例。在

另请参见:

您可以尝试以下方法:

class APSpider(BaseSpider):
name = "APSpider"

start_urls = [
    "http://www.somedomain.com/list-of-websites",
]

def __init__(self):
    self.allowed_domains = None

def parse(self, response):
    soup = BeautifulSoup( response.body )

    if not self.allowed_domains:
        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)

    if response.url in self.allowed_domains:
        yield Request(...)

...

相关问题 更多 >