2.1-Python爬虫-正则/XML/XPath/CSS选择器-案例演示

Python爬虫-正则/XML/XPath/CSS选择器

正则表达式

案例v23,re的基本使用流程

'''
python中正则模块是re
使用大致步骤:
1. compile函数讲正则表达式的字符串便以为一个Pattern对象
2. 通过Pattern对象的一些列方法对文本进行匹配,匹配结果是一个Match对象
3. 用Match对象的方法,对结果进行操纵

'''


import re

# \d表示以数字
# 后面+号表示这个数字可以出现一次或者多次
s = r"\d+" # r表示后面是原生字符串,后面不需要转义


# 返回Pattern对象
pattern = re.compile(s)

# 返回一个Match对象
# 默认找到一个匹配就返回
m = pattern.match("one12two2three3")

print(type(m))
# 默认匹配从头部开始,所以此次结果为None
print(m)

# 返回一个Match对象
# 后面为位置参数含义是从哪个位置开始查找,找到哪个位置结束
m = pattern.match("one12two2three3", 3, 10)

print(type(m))
# 默认匹配从头部开始,所以此次结果为None
print(m)


print(m.group())

print(m.start(0))
print(m.end(0))
print(m.span(0))

案例v24,match的基本使用
正则常用方法:
- match: 从开始位置开始查找,一次匹配
- search:从任何位置查找,一次匹配, 案例v25
- findall: 全部匹配,返回列表, 案例v26
- finditer: 全部匹配,返回迭代器, 案例v26
- split: 分割字符串,返回列表
- sub:替换

'''
正则结果Match的使用案例
'''

import re

# 以下正则分成了两个组,以小括号为单位
s = r'([a-z]+) ([a-z]+)'
pattern = re.compile(s, re.I) # s.I表示忽略大小写

m = pattern.match("Hello world wide web")

# goup(0)表示返回匹配成功的整个子串
s = m.group(0)
print(s)

a = m.span(0) # 返回匹配成功的 整个子串的跨度
print(a)

# gourp(1)表示返回的第一个分组匹配成功的子串
s = m.group(1)
print(s)

a = m.span(1) # 返回匹配成功的第一个子串的跨度
print(a)


s = m.groups() #等价于m.gourp(1), m.group(2).......
print(s)

匹配中文:案例v27

'''
中文unicode案例
'''


import re

hello = u'你好,世界'

pattern = re.compile(r'[\u4e00-\u9fa5]+')

m = pattern.findall(hello)
print(m)

XML

案例v28.xml

<?xml version="1.0" encoding="utf-8"?>


<bookstore>
    <book category="cooking">
        <title lang="en">Everyday Italian</title>
        <author>Gidada De</author>
        <year>2018</year>
        <price>23</price>
    </book>


    <book category="education">
        <title lang="en">Python is Python</title>
        <author>Food War</author>
        <year>2008</year>
        <price>83</price>
    </book>

    <book category="sport">
        <title lang="en">Running</title>
        <author>Klaus Kuka</author>
        <year>2010</year>
        <price>43</price>
    </book>

</bookstore>

lxml库

解析HTML,案例v29.py

'''
安装lxml
'''
from lxml import etree

'''
用lxml来解析HTML代码
'''

text = '''
<div>
    <ul>
        <li class="item-0"> <a href="0.html"> first item </a></li>
        <li class="item-1"> <a href="1.html"> first item </a></li>
        <li class="item-2"> <a href="2.html"> first item </a></li>
        <li class="item-3"> <a href="3.html"> first item </a></li>
        <li class="item-4"> <a href="4.html"> first item </a></li>
        <li class="item-5"> <a href="5.html"> first item </a>
    </ul>
</div>
'''

# 利用etree.HTML把字符串解析成HTML文档
html = etree.HTML(text)
s = etree.tostring(html)
print(s)

文件读取,案例v30.html, v31.py

<?xml version="1.0" encoding="utf-8"?>

<bookstore>
    <book category="cooking">
        <title lang="en">Everyday Italian</title>
        <author>Gidada De</author>
        <year>2018</year>
        <price>23</price>
    </book>


    <book category="education">
        <title lang="en">Python is Python</title>
        <author>Food War</author>
        <year>2008</year>
        <price>83</price>
    </book>

    <book category="sport">
        <title lang="en">Running</title>
        <author>Klaus Kuka</author>
        <year>2010</year>
        <price>43</price>
    </book>

</bookstore>
from lxml import etree

# 只能读取xml格式内容,html报错
html = etree.parse("./v30.html")

rst = etree.tostring(html, pretty_print=True)
print(rst)

etree和XPath的配合使用, 案例v32.py

from lxml import etree

# 只能读取xml格式内容,html报错
html = etree.parse("./v30.html")
print(type(html))

rst = html.xpath('//book')
print(type(rst))
print(rst)

# xpath的意识是,查找带有category属性值为sport的book元素
rst = html.xpath('//book[@category="sport"]')
print(type(rst))
print(rst)

# xpath的意识是,查找带有category属性值为sport的book元素下的year元素
rst = html.xpath('//book[@category="sport"]/year')
rst = rst[0]
print(type(rst))
print(rst.tag)
print(rst.text)

CSS选择器 BeautifulSoup4

使用BeautifulSoup4 案例v33.py


from urllib import request
from bs4 import BeautifulSoup


url = 'http://www.baidu.com'

rsp = request.urlopen(url)
content = rsp.read()

soup = BeautifulSoup(content, 'lxml')

# bs自动转码
content = soup.prettify()
print(content)

Tag
- 对应Html中的标签
- 可以通过soup.tag_name
- tag两个重要属性
- name
- attrs
** - 案例a34 **

from urllib import request
from bs4 import BeautifulSoup


url = 'http://www.baidu.com'

rsp = request.urlopen(url)
content = rsp.read()

soup = BeautifulSoup(content, 'lxml')


print("==" * 12)
tags = soup.find_all(re.compile('^me'), content="always")
for tag in tags:
    print(tag)
print("==" * 12)
  • 遍历文档对象
    • contents: tag的子节点以列表的方式给出
    • children: 子节点以迭代器形式返回
    • descendants: 所子孙节点
    • string
    • 案例34

```

猜你喜欢

转载自www.cnblogs.com/xuxaut-558/p/10031355.html