爬虫笔记day04

续正则分组例题

注意:有加括号的只输出括号里面的表达式,多个括号用元组存储

#例子:
import re
S='A B C D'
p1=re.compile('\w+\s+\w+')
p=p1.findall(S) #['A B', 'C D']
p2=re.compile('(\w+)\s+(\w+)')
p=p2.findall(S) #[('A', 'B'), ('C', 'D')]
p3=re.compile('(\w+)\s+\w+')
p=p3.findall(S) #['A', 'C']
print(p)

正则案例:

要求:重给出的html代码中提取如下内容
1、第一步实现:[('Tiger','Two...'),('Rabbit','Small...')]
2、第二步实现:
动物名称:Tiger
动物描述:Two.....
**************************
动物名称:Rabbit
动物描述:Small....
**************************

html代码:
<div class="animal">
    <p class="name">
        <a title="Tiger"></a>
    </p>
    <p class="content">
        Two tiger two tigers run fast
    </p>
</div>
<div class="animal">
    <p class="name">
        <a title="Rabbit"></a>
    </p>
    <p class="content">
        Small white rabbit white and white
    </p>
</div>
"""

实现代码:

import re
s='''
<div class="animal">
    <p class="name">
        <a title="Tiger"></a>
    </p>
    <p class="content">
        Two tiger two tigers run fast
    </p>
</div>
<div class="animal">
    <p class="name">
        <a title="Rabbit"></a>
    </p>
    <p class="content">
        Small white rabbit white and white
    </p>
</div>
'''
#正则表达式中需要删除的多余的可用.*?代替(非贪婪匹配),要提取的内容加括号即可
reg='<a title="(.*?)">.*?<p class="content">(.*?)</p>'
p1=re.compile(reg,re.S)
p=p1.findall(s)
#第一步实现:
print(p)
#第二步实现
for r in p:
    #去除前后多余的换行符和空格
    print("动物名称:",r[0].strip())
    print("动物描述:", r[1].strip())
    print('*'*50)

运行结果:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

废材终结者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值