python网络,爬虫,数据库笔记

爬虫系列(十七):Scrapy Shell

2018-01-31  本文已影响5人  文子轩

进入项目的根目录,执行下列命令来启动shell:

      scrapy shell "http://www.itcast.cn/channel/teacher.shtml"
image.png

Scrapy Shell根据下载的页面会自动创建一些方便使用的对象,例如 Response 对象,以及 Selector 对象 (对HTML及XML内容)。

Selectors选择器

Scrapy Selectors 内置 XPath 和 CSS Selector 表达式机制

Selector有四个基本的方法,最常用的还是xpath:

尝试Selector

我们用腾讯社招的网站http://hr.tencent.com/position.php?&start=0#a举例:

    # 启动
    scrapy shell "http://hr.tencent.com/position.php?&start=0#a"

    # 返回 xpath选择器对象列表
    response.xpath('//title')
    [<Selector xpath='//title' data=u'<title>\u804c\u4f4d\u641c\u7d22 | \u793e\u4f1a\u62db\u8058 | Tencent \u817e\u8baf\u62db\u8058</title'>]

    # 使用 extract()方法返回 Unicode字符串列表
    response.xpath('//title').extract()
    [u'<title>\u804c\u4f4d\u641c\u7d22 | \u793e\u4f1a\u62db\u8058 | Tencent \u817e\u8baf\u62db\u8058</title>']

    # 打印列表第一个元素,终端编码格式显示
    print response.xpath('//title').extract()[0]
    <title>职位搜索 | 社会招聘 | Tencent 腾讯招聘</title>

    # 返回 xpath选择器对象列表
    response.xpath('//title/text()')
    <Selector xpath='//title/text()' data=u'\u804c\u4f4d\u641c\u7d22 | \u793e\u4f1a\u62db\u8058 | Tencent \u817e\u8baf\u62db\u8058'>

    # 返回列表第一个元素的Unicode字符串
    response.xpath('//title/text()')[0].extract()
    u'\u804c\u4f4d\u641c\u7d22 | \u793e\u4f1a\u62db\u8058 | Tencent \u817e\u8baf\u62db\u8058'

    # 按终端编码格式显示
    print response.xpath('//title/text()')[0].extract()
    职位搜索 | 社会招聘 | Tencent 腾讯招聘

    response.xpath('//*[@class="even"]')
    职位名称:

    print site[0].xpath('./td[1]/a/text()').extract()[0]
    TEG15-运营开发工程师(深圳)
    职位名称详情页:

    print site[0].xpath('./td[1]/a/@href').extract()[0]
    position_detail.php?id=20744&keywords=&tid=0&lid=0
    职位类别:

    print site[0].xpath('./td[2]/text()').extract()[0]
    技术类

以后做数据提取的时候,可以把现在Scrapy Shell中测试,测试通过后再应用到代码中。
官方文档:http://scrapy-chs.readthedocs.io/zh_CN/latest/topics/shell.html

上一篇 下一篇

猜你喜欢

热点阅读