re模块
re(regular expression),正则表达式
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
| import re
result=re.findall(r"\d+","我今年18岁,我有200000000块") print(result)
result=re.finditer(r"\d+","我今年18岁,我有200000000块") for item in result: print(item.group())
result=re.search(r"\d+","我叫周杰伦,今年32岁,我的班级是5年4班") print(result)
result=re.search(r"\d+","我叫周杰伦,今年32岁,我的班级是5年4班") print(result)
obj=re.compile(r"\d+")
result=obj.findall("我叫周杰伦,今年32岁,我的班级是5年4班") print(result)
s=''' <div class='西游记'>span id='10010'>中国联通</span></div> <div class='西游记'><span id='10086'>中国移动</span></div> ''' obj=re.compile(r"<span id='(?P<id>\d+)'>(?P<name>.*?)</span>")
result = obj.finditer(s) for item in result: id = item.group("id") print(id)
obj =re.compile(r'<div class="item">.*?<span class="title">(?P<name>.*?)</span>',re.S)
|
bs4模块
BeautifulSoup,对标签和属性单步查找
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
| pip install bs4 from bs4 import BeautifulSoup
page=BeautifulSoup(html,"html.parser")
page.find("标签名",attrs={"属性":"值"})
li= page.find("li",attrs={"id":"abc"}) a=li.find('a') print(a.text) print(a.get('href'))
page.find_all("标签名",attrs={"属性":"值"})
li_list=page.find_all('li') for li in li_list: a=li.find('a')
img_src=div.find('img').get('src') img=requests.get(img_src)
with open(f"{img_name}.jpg",mode='wb') as f: f.write(img.content)
|
XPath解析
XPath是一门在XML文档中查找信息的语言。XPath可用来在XML文档中对元素和属性进行遍历。而我们熟知的HTML恰巧属于XML的一个子集。所以完全可以用xpath去查找html中的内容。
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
| pip install lxml
from lxml import etree
from lxml import html etree=html.etree
et=etree.XML(str) result=et.xpath('/book') result=et.xpath('/book/name') result=et.xpath('/book/name/text()') result=et.xpath('/book//nick') result=et.xpath('/book/*/nick') result=et.xpath('/book/author/nick[@class='jay']/text()') result=et.xpath('/book/author/nick[2]/text()') result=et.xpath('/book/partner/nick/@id')
et=etree.HTML(str) li_list=et.xpath('//li') for li in li_list: href=li.xpath('./a/@href') text=li.xpath('./a/text()')
|
pyquery模块
pyquery主要通过css选择器的方式处理数据 pyquery能改变HTML中的结构
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
| pip install pyquery from pyquery import PyQuery
p=PyQuery(html)
li=p('li')
a=p('li')('a') a=p('li a') a=p('.aaa a') a=p('#qq a')
href=p('#qq a').attr('href') text=p('#qq a').text()
href=p('li a').attr('href')
it=p('li a').items() for item in it: href=item.attr('href') text=item.text() html=item.html()
p('div.aaa').after('''xxx''') p('div.aaa').append('''xxx''') p('div.bbb').attr('class','aaa') p('div.bbb').remove_attr('class') p('div.bbb').remove()
|