python使用正则获取html中的时间
PHPz
PHPz 2017-04-17 11:20:11
[Python讨论组]

想做一个爬虫,使用BeautifulSoup假使获取以下内容:

<p class="authi">
<img class="authicn vm" id="" src="static/image/common/online_member.gif" />
<em id="">发表于 <span title="2013-4-2 08:30:11">4&nbsp;天前</span></em>
<span class="pipe">|</span><a href=>倒序浏览</a>
<p style="float:right;position:relative;top:-6px;"><ul>
<li style="float: left; width: 130px; height: 24px;"><wb:follow-button uid="" type="gray_2" width="136" height="24"></wb:follow-button></li>
<li style=" float:left; width: 160px; height: 24px;"></li>
</ul></p></p>

如何获取以上内容中的2013-4-2 08:30:11这个时间呢?
我试着写了一个

re.compile('^20\d{2}-\d+-\d+\s\d{2}:\d{2}:\d{2}')

可是这个在使用的时候不能匹配到时间?如何解决?谢谢!

PHPz
PHPz

学习是最好的投资!

全部回复(2)
迷茫

https://gist.github.com/greatghoul/53...

# -*- coding: utf-8 -*-
from BeautifulSoup import BeautifulSoup 
import re

def get_timestamp(html):
    soup = BeautifulSoup(html)
    authi_elems = soup.findAll('p', { 'class': 'authi' })
    for authi_elem in authi_elems:
        date_elem = authi_elem.find('span', title=re.compile(r'20\d{2}-\d+-\d+\s\d{2}:\d{2}:\d{2}'))
        print date_elem.get('title')


if __name__ == '__main__':
    html = """
    <p class="authi">
    <img class="authicn vm" id="" src="static/image/common/online_member.gif" />
    <em id="">发表于 <span title="2013-4-2 08:30:11">4&nbsp;天前</span></em>
    <span class="pipe">|</span><a href=>倒序浏览</a>
    <p style="float:right;position:relative;top:-6px;"><ul>
    <li style="float: left; width: 130px; height: 24px;"><wb:follow-button uid="" type="gray_2" width="136" height="24"></wb:follow-button></li>
    <li style=" float:left; width: 160px; height: 24px;"></li>
    </ul></p></p>
    """

    get_timestamp(html)
PHP中文网
re.compile('20\d{2}-\d+-\d+\s\d{2}:\d{2}:\d{2}')
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号