python使用正则获取html中的时间

 Chloemw 发布于 2022-11-07 22:46

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

发表于 4 天前 |倒序浏览

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

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

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

2 个回答
  • re.compile('20\d{2}-\d+-\d+\s\d{2}:\d{2}:\d{2}')
    2022-11-12 01:40 回答
  • 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)
    2022-11-12 01:40 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有