如何添加在scrapy python中手动创建的额外网址?

Kyl*_*son 3 python scrapy

我正在使用 Scrapy Python 来抓取网站并从某些页面中提取一些信息。有些页面在我能够抓取的整个内容中都有 ID 号,但不会显示为蜘蛛的真实 URL。我可以手动找到它们并使用 ID 构建 url,但是如何将它们发送给蜘蛛进行抓取?

在下面的函数 parse_product_abc 中,我可以获得一堆 itemid。如果我遍历它们,我可以构建新的 url 来抓取。我怎样才能告诉蜘蛛爬行?

class AbcSpider(CrawlSpider):
    name = "abc"
    allowed_domains = ["www.example.com"]
    start_urls = ['http://www.example.com/']
    rules = (
        Rule(
            # follow category pages
            LinkExtractor(
                allow=[r'/cat/abc.+/C\-abc.{6,14}$'],
                deny=('-something1-','-something2-','-something3-')
            ),
            follow=True,
            callback='parse_category_abc'
        ),
        Rule(
            # parse product pages
            LinkExtractor(
                allow=[r'/prd/[A-z0-9\-]+/\d{9}$'],
                deny=('-something1-','-something2-','-something3-')
                )
            ),
            follow=False,
            callback='parse_product_abc'
        )
    )
    def parse_product_abc(self, response):
        # grab json array from html
        product_json = response.xpath('//body').re_first(r'ABC\.PID\.Data\((.*)\);')
        product_obj  = json.loads(product_json)
        itemId       = product_obj['itemId']
        item = AbcItem()
        item['abc_itemId'] = int(itemId)
        item['abc_item']   = product_obj
        item['abc_url']   = response.url
        item['time']   = datetime.datetime.now()
        item['spider'] = self.name
        # find more data-pid attributes in html...
        itemids = response.xpath('//@data-pid').extract()
        # connect to mongo and see if new item found or not...
        connection = MongoClient(self.settings.get('MONGO_URI'))
        db = connection.abc_data
        if db['products_abc'].find_one({"abc_itemId":int(itemId)}):
            # duplicate item
            print ' '
            print 'DUP: %s' % itemId
            print 'DUP: %s' % item['abc_url']
        else:
            # new item found
            print ' '
            print 'NEW: %s' % itemId
            print 'NEW: %s' % item['abc_url']
            yield item
    def parse_category_abc(self, response):
        print 'CATEGORY: %s' % response.url
Run Code Online (Sandbox Code Playgroud)

And*_* H. 5

  1. 导入请求类:

    from scrapy.http import Request
    
    Run Code Online (Sandbox Code Playgroud)

假设http://foo.bar/items/45653是一个产品/项目 URL,45653是产品/项目 ID

  1. 循环遍历这些产品/项目 ID 并为它们中的每一个生成一个 URL,然后向每个 URL 生成一个请求,并回调到某个解析方法:

    for pid in response.xpath('//@data-pid').extract():
        url = "http://foo.bar/items/{}".format(pid)
        yield Request(url, callback=self.parse_product_abc)
    
    Run Code Online (Sandbox Code Playgroud)

我不知道您是否会使用self.parse_product_abc或其他方法作为回调,但您可以这样做。