1.Scrapy爬虫之静态网页爬取之一 了解response.xpath()

我们直接看例子:
网址:http://quotes.toscrape.com/

《1.Scrapy爬虫之静态网页爬取之一 了解response.xpath()》 1

1. xpath提取方法:
用谷歌浏览器打开网页,右键检查,选中标签-copy-copyxpath

《1.Scrapy爬虫之静态网页爬取之一 了解response.xpath()》 2

copyxpath得到:/html/body/div/div[2]/div[1]/div[1]/span[1]

2.如何得到网页信息:
在jupyter中的terminal中(jupyter中的termimal不能运行在windows系统中) 输入 scrapy shell http://quotes.toscrape.com/
会有请求信息返回,返回response对象,里面包含网页所有信息。
楼主安装了3.6的anaconda,但是里面没集成scrapy框架。但是也安装了python2.7,里面成功安装了scrapy(添加环境变量了,命令行任意位置识别scrapy命令,不添加环境变量的话,只在它的文件夹下识别这个命令)。打开windows命令行,同样键入:scrapy shell http://quotes.toscrape.com/ 会有请求信息返回。[s]开头
如下:

《1.Scrapy爬虫之静态网页爬取之一 了解response.xpath()》 3

《1.Scrapy爬虫之静态网页爬取之一 了解response.xpath()》 4
《1.Scrapy爬虫之静态网页爬取之一 了解response.xpath()》 5

response是请求后所返回的对象,200说明返回正确
要验证表达式对不对,会返回一个对象叫response,这个response包含了这个网页的所有内容:

>>>response.xpath('/html/body/div/div[2]/div[1]/div[1]/span[1]/text()')
>>> response.xpath('/html/body/div/div[2]/div[1]/div[1]/span[1]/text()').extract()```
比较:一个返回对象,一个返回列表,一个返回字符串

response.xpath(‘/html/body/div/div[2]/div[1]/div[1]/span[1]/text()’)
response.xpath(‘/html/body/div/div[2]/div[1]/div[1]/span[1]/text()’).extract()
[u’\u201cThe world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.\u201d’]
response.xpath(‘/html/body/div/div[2]/div[1]/div[1]/span[1]/text()’).extract_first()
u’\u201cThe world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.\u201d’“`
response中自带的xpath函数来验证路径表达式是不是对的,这是利用chrome自带的工具定位元素,以上验证出来了网页内标签的内容,说明是正确的。

3.如何自己写xpath获取同一标签下的所有信息:

《1.Scrapy爬虫之静态网页爬取之一 了解response.xpath()》 6

方法:所有的框都是在span class=”text”中

《1.Scrapy爬虫之静态网页爬取之一 了解response.xpath()》 7

>>> response.xpath('//span[@class="text"]/text()').extract()```
分析:response是之前scrapy shell+网页请求后返回来一个所有的对象。它的xpath函数里面是路径表达式,//表示取出所有对象,@表示属性,写完后返回的是对象,所以返回文本加上.extract()返回了一个列表:抽出的是名言
如下:
![8](http://upload-images.jianshu.io/upload_images/5076126-c4a786c56eefb44e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
抽出作者:
![9](http://upload-images.jianshu.io/upload_images/5076126-6bb485b4996cc0b3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
退出:
![10](http://upload-images.jianshu.io/upload_images/5076126-1f3186bdcbfedfa1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

**总结:**scrapy shell 算是一个工具,来验证抽取的对不对,对的话就可以大胆的去写代码了。

补充:scrapy的命令

![Paste_Image.png](http://upload-images.jianshu.io/upload_images/5076126-724447a95bb6690c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
    原文作者:siro刹那
    原文地址: https://www.jianshu.com/p/b05d0ebbbcc6
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞