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

数据提取

结构化数据: 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"))
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')

语法使用示例:

jsonpathresult
$.store.book[*].authorstore中的所有的book的作者
$..author所有的作者
$.store.*store下的所有的元素
$.store..pricestore中的所有的内容的价格
$..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>
路径表达式结果
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()")

我们取到属性,或者是文本的时候,返回字符串 但是如果我们取到的是一个节点,返回的是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')

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值