peng104

一,正则表达式解析

re正则就不写了,前面已经写入一篇很详细的正则表达式模块了~

而且,在爬虫中,下面两种方式用的多一些~

正则表达式:https://www.cnblogs.com/peng104/p/9619801.html

大致用法:

pattern = re.compile(\'<dd>.*?board-index.*?>(\d+)</i>.*?src="(.*?)".*?name"><a\'
                     +\'.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>\'
                     +\'.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>\', re.S)
items = re.findall(pattern, html)

二,Xpath解析

简介及安装

简介:XPath 是一门在 XML 文档中查找信息的语言。XPath 可用来在 XML 文档中对元素和属性进行遍历。XPath 是 W3C XSLT 标准的主要元素,并且 XQuery 和 XPointer 都构建于 XPath 表达之上。

安装:pip install lxml

调用方法:

# 先导包
from lxml import etree

# 将html文档或者xml文档转换成一个etree对象,然后调用对象中的方法查找指定的节点
# 1. 本地文件
tree = etree.parse(文件名)
tree.xpath("xpath表达式")

# 2. 网络数据
tree = etree.HTML(网页内容字符串)
tree.xpath("xpath表达式")

语法简介

先准备一个HTML格式的字符串

html_doc = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div class="d1">
    <div class="d2">
            <p class="story">
                <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" id="link3">Tillie</a>
            </p>
    </div>
    <div>
        <p id="p1">人生苦短</p>
        <p id="p2">我用python</p>
    </div>
</div>

<div class="d3">
    <a href="http://www.baidu.com">baidu</a>
    <p>百度</p>
</div>

</body>
</html>
"""
变量准备

1,选取节点

nodename     # 选取nodename节点的所有子节点         xpath(‘//div’)         # 选取了所有div节点
/            # 从根节点选取                        xpath(‘/div’)          # 从根节点上选取div节点
//           # 选取所有的当前节点,不考虑他们的位置    xpath(‘//div’)         # 选取所有的div节点
.            # 选取当前节点                        xpath(‘./div’)         # 选取当前节点下的div节点
..           # 选取当前节点的父节点                 xpath(‘..’)            # 回到上一个节点
@            # 选取属性                           xpath(’//@calss’)     # 选取所有的class属性

#######################⬇例子⬇######################

ret=selector.xpath("//div")
ret=selector.xpath("/div")
ret=selector.xpath("./div")
ret=selector.xpath("//p[@id=\'p1\']")
ret=selector.xpath("//div[@class=\'d1\']/div/p[@class=\'story\']")

2,谓语

表达式                                         结果
xpath(‘/body/div[1]’)                     # 选取body下的第一个div节点
xpath(‘/body/div[last()]’)                # 选取body下最后一个div节点
xpath(‘/body/div[last()-1]’)              # 选取body下倒数第二个div节点
xpath(‘/body/div[positon()<3]’)           # 选取body下前两个div节点
xpath(‘/body/div[@class]’)                # 选取body下带有class属性的div节点
xpath(‘/body/div[@class=”main”]’)         # 选取body下class属性为main的div节点
xpath(‘/body/div[@price>35.00]’)          # 选取body下price元素值大于35的div节点

#######################⬇例子⬇######################

ret=selector.xpath("//p[@class=\'story\']//a[2]")
ret=selector.xpath("//p[@class=\'story\']//a[last()]")

3,通配符

Xpath通过通配符来选取未知的XML元素

表达式                 结果
xpath(’/div/*’)     # 选取div下的所有子节点
xpath(‘/div[@*]’)    # 选取所有带属性的div节点

#######################⬇例子⬇######################

ret=selector.xpath("//p[@class=\'story\']/*")
ret=selector.xpath("//p[@class=\'story\']/a[@class]")

4,取多个路径

使用 “|” 运算符可以选取多个路径

表达式                         结果
xpath(‘//div|//table’)    # 选取所有的div和table节点

#######################⬇例子⬇######################

ret=selector.xpath("//p[@class=\'story\']/a[@class]|//div[@class=\'d3\']")
print(ret)

5,Xpath轴

轴可以定义相对于当前节点的节点集

轴名称                      表达式                                  描述
ancestor                xpath(‘./ancestor::*’)              # 选取当前节点的所有先辈节点(父、祖父)
ancestor-or-self        xpath(‘./ancestor-or-self::*’)      # 选取当前节点的所有先辈节点以及节点本身
attribute               xpath(‘./attribute::*’)             # 选取当前节点的所有属性
child                   xpath(‘./child::*’)                 # 返回当前节点的所有子节点
descendant              xpath(‘./descendant::*’)            # 返回当前节点的所有后代节点(子节点、孙节点)
following               xpath(‘./following::*’)             # 选取文档中当前节点结束标签后的所有节点
following-sibing        xpath(‘./following-sibing::*’)      # 选取当前节点之后的兄弟节点
parent                  xpath(‘./parent::*’)                # 选取当前节点的父节点
preceding               xpath(‘./preceding::*’)             # 选取文档中当前节点开始标签前的所有节点
preceding-sibling       xpath(‘./preceding-sibling::*’)     # 选取当前节点之前的兄弟节点
self                    xpath(‘./self::*’)                  # 选取当前节点

6,功能函数

使用功能函数能够更好的进行模糊搜索

函数                  用法                                                               解释
starts-with         xpath(‘//div[starts-with(@id,”ma”)]‘)                        # 选取id值以ma开头的div节点
contains            xpath(‘//div[contains(@id,”ma”)]‘)                           # 选取id值包含ma的div节点
and                 xpath(‘//div[contains(@id,”ma”) and contains(@id,”in”)]‘)    # 选取id值包含ma和in的div节点
text()              xpath(‘//div[contains(text(),”ma”)]‘)                        # 选取节点文本包含ma的div节点

Element对象

from lxml.etree import _Element
for obj in ret:
    print(obj)
    print(type(obj))  # from lxml.etree import _Element

\'\'\'
Element对象

class xml.etree.ElementTree.Element(tag, attrib={}, **extra)

  tag:string,元素代表的数据种类。
  text:string,元素的内容。
  tail:string,元素的尾形。
  attrib:dictionary,元素的属性字典。
  
  #针对属性的操作
  clear():清空元素的后代、属性、text和tail也设置为None。
  get(key, default=None):获取key对应的属性值,如该属性不存在则返回default值。
  items():根据属性字典返回一个列表,列表元素为(key, value)。
  keys():返回包含所有元素属性键的列表。
  set(key, value):设置新的属性键与值。

  #针对后代的操作
  append(subelement):添加直系子元素。
  extend(subelements):增加一串元素对象作为子元素。#python2.7新特性
  find(match):寻找第一个匹配子元素,匹配对象可以为tag或path。
  findall(match):寻找所有匹配子元素,匹配对象可以为tag或path。
  findtext(match):寻找第一个匹配子元素,返回其text值。匹配对象可以为tag或path。
  insert(index, element):在指定位置插入子元素。
  iter(tag=None):生成遍历当前元素所有后代或者给定tag的后代的迭代器。#python2.7新特性
  iterfind(match):根据tag或path查找所有的后代。
  itertext():遍历所有后代并返回text值。
  remove(subelement):删除子元素。
\'\'\'

三,BeautifulSoup

简介及安装

简介:

    Beautiful Soup提供一些简单的、python式的函数用来处理导航、搜索、修改分析树等功能。
    它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序。

安装:pip3 install beautifulsoup4

解析器:

    Beautiful Soup支持Python标准库中的HTML解析器,还支持一些第三方的解析器,如果我们不安装它,则 Python 会使用 Python默认的解析器,lxml 解析器更加强大,速度更快

官方文档

简单使用

使用方式:可以将一个html文档,转化为BeautifulSoup对象,然后通过对象的方法或者属性去查找指定的节点内容

from bs4 import BeautifulSoup

# 转化本地文件
soup = BeautifulSoup(open(\'本地文件\'), \'lxml\')

# 转化网络文件
soup = BeautifulSoup(\'字符串类型或者字节类型\', \'lxml\')

# 从文档中获取所有文字内容:
print(soup.get_text())

语法简介

# 1.根据标签名查找
    - soup.a   只能找到第一个符合要求的标签
# 2.获取属性
    - soup.a.attrs  获取a所有的属性和属性值,返回一个字典
    - soup.a.attrs[\'href\']   获取href属性
    - soup.a[\'href\']   也可简写为这种形式
# 3.获取内容
    - soup.a.string
    - soup.a.text
    - soup.a.get_text()
   注意:如果标签还有标签,那么string获取到的结果为None,而其它两个,可以获取文本内容
# 4.find:找到第一个符合要求的标签
    - soup.find(\'a\')  找到第一个符合要求的
    - soup.find(\'a\', title="xxx")
    - soup.find(\'a\', alt="xxx")
    - soup.find(\'a\', class_="xxx")
    - soup.find(\'a\', id="xxx")
# 5.find_all:找到所有符合要求的标签
    - soup.find_all(\'a\')
    - soup.find_all([\'a\',\'b\']) 找到所有的a和b标签
    - soup.find_all(\'a\', limit=2)  限制前两个
# 6.根据选择器选择指定的内容
           select:soup.select(\'#feng\')
    - 常见的选择器:标签选择器(a)、类选择器(.)、id选择器(#)、层级选择器
        - 层级选择器:
            div .dudu #lala .meme .xixi  下面好多级
            div > p > a > .lala          只能是下面一级
    注意:select选择器返回永远是列表,需要通过下标提取指定的对象

find_all()

先准备一个HTML格式的字符串

html_doc = """
<html><head><title>The Dormouse\'s story</title></head>
<body>
<p id="my p" class="title"><b id="bbb" class="boldest">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>
"""
变量准备

1,五种过滤器

字符串、正则表达式、列表、True、方法

from bs4 import BeautifulSoup
soup=BeautifulSoup(html_doc,\'lxml\')


#1、字符串:即标签名
print(soup.find_all(\'b\'))

#2、正则表达式
import re
print(soup.find_all(re.compile(\'^b\'))) #找出b开头的标签,结果有body和b标签

#3、列表:如果传入列表参数,Beautiful Soup会将与列表中任一元素匹配的内容返回.下面代码找到文档中所有<a>标签和<b>标签:
print(soup.find_all([\'a\',\'b\']))

#4、True:可以匹配任何值,下面代码查找到所有的tag,但是不会返回字符串节点
print(soup.find_all(True))
for tag in soup.find_all(True):
    print(tag.name)

#5、方法:如果没有合适过滤器,那么还可以定义一个方法,方法只接受一个元素参数 ,如果这个方法返回 True 表示当前元素匹配并且被找到,如果不是则反回 False
def has_class_but_no_id(tag):
    return tag.has_attr(\'class\') and not tag.has_attr(\'id\')
print(soup.find_all(has_class_but_no_id))

2、按照类名查找

注意:关键字是class_,class_=value,value可以是五种选择器之一

print(soup.find_all(\'a\',class_=\'sister\')) # 查找类为sister的a标签
print(soup.find_all(\'a\',class_=\'sister ssss\')) # 查找类为sister和sss的a标签,顺序错误也匹配不成功
print(soup.find_all(class_=re.compile(\'^sis\'))) # 查找类为sister的所有标签

3、attrs

print(soup.find_all(\'p\',attrs={\'class\':\'story\'}))

4、text

值可以是:字符,列表,True,正则

print(soup.find_all(text=\'Elsie\'))
print(soup.find_all(\'a\',text=\'Elsie\'))

5、limit参数

如果文档树很大那么搜索会很慢.如果我们不需要全部结果,可以使用 limit 参数限制返回结果的数量.效果与SQL中的limit关键字类似,当搜索到的结果数量达到 limit 的限制时,就停止搜索返回结果

print(soup.find_all(\'a\',limit=2))

6、recursive

调用tag的 find_all() 方法时,Beautiful Soup会检索当前tag的所有子孙节点,如果只想搜索tag的直接子节点,可以使用参数 recursive=False .

print(soup.html.find_all(\'a\'))
print(soup.html.find_all(\'a\',recursive=False))

tag

像调用 find_all() 一样调用tag find_all() 几乎是Beautiful Soup中最常用的搜索方法,所以我们定义了它的简写方法. BeautifulSoup 对象和 tag 对象可以被当作一个方法来使用~

这个方法的执行结果与调用这个对象的 find_all() 方法相同~

# 下面两行代码是等价的:
soup.find_all("a")
soup("a")

# 这两行代码也是等价的:
soup.title.find_all(text=True)
soup.title(text=True)

find

find( name , attrs , recursive , text , **kwargs )

find_all() 方法将返回文档中符合条件的所有tag,尽管有时候我们只想得到一个结果.比如文档中只有一个<body>标签,那么使用 find_all() 方法来查找<body>标签就不太合适, 使用 find_all 方法并设置 limit=1 参数不如直接使用 find() 方法

下面两行代码是等价的:

soup.find_all(\'title\', limit=1)
# [<title>The Dormouse\'s story</title>]
soup.find(\'title\')
# <title>The Dormouse\'s story</title>

唯一的区别是 find_all() 方法的返回结果是值包含一个元素的列表,而 find() 方法直接返回结果.
find_all() 方法没有找到目标是返回空列表, find() 方法找不到目标时,返回 None .

print(soup.find("nosuchtag"))
# None

soup.head.title 是 tag的名字 方法的简写.这个简写的原理就是多次调用当前tag的 find() 方法:

soup.head.title
# <title>The Dormouse\'s story</title>
soup.find("head").find("title")
# <title>The Dormouse\'s story</title>

 

分类:

技术点:

相关文章: