程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

python面试题(7)

python杂谈(0)

标签  

python面试题(7)

python电子书(56)

日期归档  

爬虫基础--数据提取方法

发布于2019-08-22 17:46     阅读(688)     评论(0)     点赞(26)     收藏(4)


数据提取

结构化数据: json,xml
非结构化数据:Html,字符串
结构化数据处理的方式有:jsonpath,xpath,转换python类型处理,bs4
非结构化数据处理方式有:正则表达式,xpath,bs4

1.用json模块提取数据

在这里插入图片描述
类文件对象的理解:

具有read()或者write()方法的对象就是类文件对象,比如f = open(“a.txt”,”r”) f就是类文件对象

具体使用方法:

mydict = {
        "name": "孙威",
        "age": 16
    }
#json.dumps 实现python类型转化为json字符串
#indent实现换行和空格
#ensure_ascii=False实现让中文写入的时候保持为中文
json_str = json.dumps(mydict,indent=2,ensure_ascii=False)

#json.loads 实现json字符串转化为python的数据类型
my_dict = json.loads(json_str)

#json.dump 实现把python类型写入类文件对象
with open("temp.txt","w") as f:
    json.dump(mydict,f,ensure_ascii=False,indent=2)

# json.load 实现类文件对象中的json字符串转化为python类型
with open("temp.txt","r") as f:
    my_dict = json.load(f)
# 或者my_dict = json.load(open("temp.txt","r"))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

jsonpath模块提取数据

jsonpath用来解析多层嵌套的json数据;JsonPath 是一种信息抽取类库,是从JSON文档中抽取指定信息的工具,提供多种语言实现版本,包括:Javascript, Python, PHP 和 Java。

jsonpath 语法描述
$ 根节点
@ 现行节点
. or [] 子节点
. . 不管位置,选取所有符合条件的条件
* 匹配所有元素节点
[] 迭代器标识,可以在里面做简单的迭代操作,如数组下标,根据内容选值
[,] 支持迭代器中做多选
?() 支持过滤操作
() 支持表达式计算
- 不支持去父节点
- 不支持属性访问
- 不支持分组
# 语法使用示例
data = { "store": {
    "book": [ 
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      { "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      { "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  }
}
# 转换成json格式的数据
data_dict = json.loads(data)
# 解析数据,返回的是所有的author
result_list = jsonpath.jsonpath(data_dict, '$..author')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

语法使用示例:

jsonpath result
$.store.book[*].author store中的所有的book的作者
$..author 所有的作者
$.store.* store下的所有的元素
$.store..price store中的所有的内容的价格
$..book[2] 第三本书
$..book[(@.length-1)] | $..book[-1:] 最后一本书
$..book[0,1] | $..book[:2] 前两本书
$..book[?(@.isbn)] 获取有isbn的所有数
$..book[?(@.price<10)] 获取价格大于10的所有的书
$..* 获取所有的数据

2.正则表达式提取数据

3.xpath语法

XPath (XML Path Language) 是一门在 HTML\XML 文档中查找信息的语言,可用来在 HTML\XML 文档中对元素和属性进行遍历。
xpath语法

表达式 描述
nodename 选中该元素。
/ 从根节点选取、或者是元素和元素间的过渡。
// 从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置。
. 选取当前节点。
.. 选取当前节点的父节点。
@ 选取属性。
text() 选取文本。

实例

<bookstore>

<book>
  <title lang="eng">Harry Potter</title>
  <price>29.99</price>
</book>

<book>
  <title lang="eng">Learning XML</title>
  <price>39.95</price>
</book>

</bookstore>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
路径表达式 结果
bookstore 选择bookstore元素。
/bookstore 选取根元素 bookstore。注释:假如路径起始于正斜杠( / ),则此路径始终代表到某元素的绝对路径!
bookstore/book 选取属于 bookstore 的子元素的所有 book 元素。
//book 选取所有 book 子元素,而不管它们在文档中的位置。
bookstore//book 选择属于 bookstore 元素的后代的所有 book 元素,而不管
//book/title/@lang 选择所有的book下面的title中的lang属性的值。
//book/title/text() 选择所有的book下面的title的文本。
//title[@lang=“eng”] 选择lang属性值为eng的所有title元素
/bookstore/book[1] 选取属于 bookstore 子元素的第一个 book 元素。
/bookstore/book[last()] 选取属于 bookstore 子元素的最后一个 book 元素。
/bookstore/book[last()-1] 选取属于 bookstore 子元素的倒数第二个 book 元素。
/bookstore/book[position()>1] 选择bookstore下面的book元素,从第二个开始选择
//book/title[text()=‘Harry Potter’] 选择所有book下的title元素,仅仅选择文本为Harry Potter的title元素
/bookstore/book[price>35.00]/title 选取 bookstore 元素中的 book 元素的所有 title 元素,且其中的 price 元素的值须大于 35.00。
/bookstore/* 选取 bookstore 元素的所有子元素。
//* 选取文档中的所有元素。
//title[@*] 选取所有带有属性的 title 元素。

注意点: 在xpath中,第一个元素的位置是1,最后一个元素的位置是last(),倒数第二个是last()-1

4.lxml模块

lxml是一款高性能的 Python HTML/XML 解析器,我们可以利用XPath,来快速的定位特定元素以及获取节点信息

text = ''' <div> <ul> 
        <li class="item-1"><a href="link1.html">first item</a></li> 
        <li class="item-1"><a href="link2.html">second item</a></li> 
        <li class="item-inactive"><a href="link3.html">third item</a></li> 
        <li class="item-1"><a href="link4.html">fourth item</a></li> 
        <li class="item-0"><a href="link5.html">fifth item</a> 
        </ul> </div> '''
# 导入lxml 的 etree 库
from lxml import etree
# 利用etree.HTML,将字符串转化为Element对象,Element对象具有xpath的方法
html = etree.HTML(text) 
#获取href的列表和title的列表
href_list = html.xpath("//li[@class='item-1']/a/@href")
title_list = html.xpath("//li[@class='item-1']/a/text()")

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

我们取到属性,或者是文本的时候,返回字符串 但是如果我们取到的是一个节点,返回的是element对象,可以继续使用xpath方法

5.BeautifulSoup4

和 lxml 一样,Beautiful Soup 也是一个HTML/XML的解析器,lxml 只会局部遍历,而Beautiful Soup 是基于HTML DOM的,会载入整个文档,解析整个DOM树,因此时间和内存开销都会大很多,所以性能要低于lxml。

html = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
# 导入 bs4 库
from bs4 import BeautifulSoup
#创建 Beautiful Soup 对象
soup = BeautifulSoup(html)

# 传字符串
print soup.find_all('a')
#[<a class="sister" href="http://example.com/elsie" id="link1"><!-- Elsie --></a>, <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>]

# 传正则表达式
soup.find_all(re.compile("^b"))

# 传列表

# keyword 参数
soup.find_all(class = "sister")

# text 参数
soup.find_all(text="Elsie")

# (1)通过标签选择器查找
print soup.select('title') 

# (2)通过类选择器查找
print soup.select('.sister')

# (3)通过 id 选择器查找
print soup.select('#link1')

# (4)层级选择器 查找
print soup.select('p #link1')

# (5)通过属性选择器查找
print soup.select('a[class="sister"]')

# (6) 获取文本内容 get_text()
for title in soup.select('title'):
    print title.get_text()

# (7) 获取属性 get('属性的名字')
print soup.select('a')[0].get('href')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

find_all(name, attrs, recursive, text, **kwargs)
查找所有名字为 name 的标签
CSS选择器
通过标签选择器查找



所属网站分类: 技术文章 > 博客

作者:熊猫烧香

链接:https://www.pythonheidong.com/blog/article/53280/89fd733fa6eb360be517/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

26 0
收藏该文
已收藏

评论内容:(最多支持255个字符)