繁体   English   中英

scrapy从数据库中获取start_urls

[英]scrapy get start_urls from database

我有一个问题想问
如果我想从数据库中选择链接并让它成为start_urls
我能做什么 ??

我的数据库保存这些链接和标题

1: link : 'http://test.com/id=1'  ,  title : 'math'   
2: link : 'http://test.com/id=2'  ,  title : 'english'       
3: link : 'http://test.com/id=30' ,  title : 'sports'    

如果我能把标题作为我的蜘蛛中的参数会更好。

这是我的想法:

class MySpider(Spider):  
    name = "linktest"
    for obj in Learning.objects.all():
        print obj.link
        #result: http://test.com/id=1
                 http://test.com/id=2
                 http://test.com/id=30
    start_urls =[ 'http://test.com/id=1',  #how to do this?
                  'http://test.com/id=2',
                  'http://test.com/id=30' ]

    def parse(self, response):
        #item['title']=math     #when response.url ==  http://test.com/id=1,
        #item['title']=english  #when response.url ==  http://test.com/id=2,...

你需要重写start_requests()方法和yield / return Request从它的实例:

此方法必须返回一个带有第一个爬网请求的iterable。

当没有指定特定URL时打开蜘蛛进行抓取时,这是Scrapy调用的方法。

class MySpider(Spider):  
    name = "linktest"

    def start_requests(self):
        for obj in Learning.objects.all():
            yield Request(obj.link)

obj.title传递给回调,请使用meta属性:

class MySpider(Spider):  
    name = "linktest"

    def start_requests(self):
        for obj in Learning.objects.all():
            yield Request(obj.link, meta={'title': obj.title})

    def parse(self, response):
        print response.url, response.meta['title']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM