鱼C论坛

 找回密码
 立即注册
查看: 776|回复: 2

新手在看scrapy的说明文档遇到一点问题

[复制链接]
发表于 2018-5-16 00:02:03 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
代码:page = response.url.split("/")[-2]
前面都能看懂,就是后面跟着这个[-2]是什么意思?
完整代码:
import scrapy

class QuotesSpider(scrapy.Spider):
    name = "quotes"

    def start_requests(self):
        urls = [
            'http://quotes.toscrape.com/page/1/',
            'http://quotes.toscrape.com/page/2/',
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        page = response.url.split("/")[-2]
        filename = 'quotes-%s.html' % page
        with open(filename, 'wb') as f:
            f.write(response.body)
        self.log('Saved file %s' % filename)

我试着查了查,没有度娘到。所以来问一下大哥们。希望这不是一个蠢问题……
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2018-5-16 08:01:07 | 显示全部楼层
split可以看成是【切片操作】,[-2]表示倒数第二个【分片】。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-5-16 09:01:08 | 显示全部楼层
举个栗子你就懂啦,建议楼主回顾下之前的学习内容 :)
  1. >>> tmp = 'http://www.baidu.com'
  2. >>> tmp[-1]
  3. 'm'
  4. >>> tmp[-2]
  5. 'o'
  6. >>> tmp.split(sep='.')
  7. ['http://www', 'baidu', 'com']
  8. >>> tmp.split(sep='.')[-2]
  9. 'baidu'
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-12-30 05:58

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表