前言
- 在使用
Scrapy
框架爬取页面数据的时候经常会出现数据获取不到或者数据并非想要的数据,于是对这里面的get()
、getall()
、extract()
、extract_first()
函数的使用进行记录。
分析
一般使用
response.xpath()
解析得到的是一个SelectorList
列表,可以使用type(response.xpath())
查看。SelectorList
里面存放的是多个Selector
对象。测试:
1
2
3
4
5
6scrapy shell http://www.baidu.com
"//span//input/@value") res = response.xpath(
res
[<Selector xpath='//span//input/@value' data=''>, <Selector xpath='//span//input/@value' data='百度一下'>]
type(res)
<class 'scrapy.selector.unified.SelectorList'>
对于
SelectorList
,getall()
与extract()
函数会得到所有的数据,包括制表符和换行符等。get()
和extract_first()
都会获得列表第一个元素的数据。测试:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16res.get()
''
type(res.get())
<class 'str'>
>>> res.getall()
['', '百度一下']
type(res.getall())
<class 'list'>
>>> res.extract()
['', '百度一下']
type(res.extract())
<class 'list'>
>>> res.extract_first()
''
>>> type(res.extract_first())
<class 'str'>
对于
Selector
,getall()
与extract()
函数会得到所有的数据(一个元素的情况下,getall()
得到的是一个列表,extract()
得到的是字符串。多个元素都是列表)。get()
会获得元素的数据,extract_first()
会出错。测试:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
181]) type(res[
<class 'scrapy.selector.unified.Selector'>
>>> res[1].get()
'百度一下'
>>> type(res[1].get())
<class 'str'>
>>> res[1].getall()
['百度一下']
>>> type(res[1].getall())
<class 'list'>
>>> res[1].extract()
'百度一下'
>>> type(res[1].extract())
<class 'str'>
>>> res[1].extract_first()
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Selector' object has no attribute 'extract_first'
结论
- 对于
scrapy.selector.unified.SelectorList
对象,getall() == extract()
返回字符串,get() == extract_first()
返回列表。 - 对于
scrapy.selector.unified.Selector
对象,get() != extract_first()
,getall()与extract()看元素个数多少