python实训day02

html解析方法

  1. 正则表达式
import re
text1='abcdefg'
pattern1=re.compile(r'c')
matcher1=re.search(pattern1,text1)
print(matcher1[0])

text2="""
<html>
aaa<h1>aa
bbb
</h1>
aaa
</html>
"""
pattern2=re.compile(r'<h1>(.*?)</h1>',re.S)
print(pattern2.findall(text2))

2.bs库

#beautiful_soup库
from bs4 import BeautifulSoup
html="""
<html>
    <body>
        <a id="aa" herf="https://www.baidu.com">百度一下</a>
        <a></a>
        <h1>hello</h1>
    </body>
</html>
"""
bs=BeautifulSoup(html,'html.parser')
print(bs.a)
print(bs.find_all('a'))
print(bs.a['herf'])
print(bs.a)

3.xpath(推荐使用)

from lxml import etree
html = """(同上的html内容一样)
dom = etree.HTML(html)
#把长字符中物html文档树
print(dom)
#全文匹配,匹配不到返回[], 匹配到的[element, element]
print(dom.xpath('//a/@href'))
# /表示往下一层 //忽略任意层父级目获
# //a=/body/ul/11/a
# ichtmI元索 望的属性
# /@href 取元者属性值
#取元素内容/text()
print(dom. xpath(' //a/text()'))
#属性过滤
print(dom.xpath('//a[@id="second_a"]/text()'))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值