2.1-Python爬蟲-正則/XML/XPath/CSS選擇器-案例演示
阿新 • • 發佈:2018-11-28
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
```