Skip to main content
 首页 » 编程设计

python之如何通过命令生成 url 让 scrapy 爬行

2024年10月25日11sharpest

这是我的代码:

def parse(self, response):   
    selector = Selector(response) 
    sites = selector.xpath("//h3[@class='r']/a/@href") 
    for index, site in enumerate(sites): 
        url =  result.group(1)  
        print url 
        yield Request(url = site.extract(),callback = self.parsedetail) 
 
def parsedetail(self,response): 
    print response.url 
    ... 
    obj = Store.objects.filter(id=store_obj.id,add__isnull=True) 
    if obj: 
    obj.update(add=add) 

在 def 解析中 scarpy 将从谷歌获取 url url 输出如下:

www.test.com 
www.hahaha.com 
www.apple.com 
www.rest.com 

但是当它屈服于 def parsedetail 网址不符合顺序,可能会变成:

www.rest.com 
www.test.com 
www.hahaha.com 
www.apple.com 

有什么办法可以让 yield url 和 order 发送到 def parsedetail 吗?
因为我需要先抓取www.test.com。(top url在google搜索中提供的数据更正确)
如果里面没有数据。
我将转到下一个网址,直到更新空字段。(www.hahaha.com ,www.apple.com,www.rest.com )
请指导我谢谢!

请您参考如下方法:

默认情况下,Scrapy 请求的调度和发送顺序是没有定义的。但是,您可以使用 priority keyword argument 控制它:

priority (int) – the priority of this request (defaults to 0). The priority is used by the scheduler to define the order used to process requests. Requests with a higher priority value will execute earlier. Negative values are allowed in order to indicate relatively low-priority.


您还可以通过在 meta 字典中传递 callstack 使爬行同步,例如参见 this answer .