重温如何从网页中提取时间

时间:2015-12-09 01:41:54

标签: python regex beautifulsoup

我正在为Udemy做一些工作。我需要提取每个讲座的时间,以便我可以将它们放入我的老板进行跟踪。我已经阅读了BeautifulSoup。我已经到了时间的班级:

<div class="ci-details-container clearfix">
            <span class="ci-details">
                <i ng-class="::getCurrentLectureIcon()" class="icon-play-sign"></i>
                <span>02:29</span>
                <!-- ngIf: ::!elementData.content_summary -->
            </span>

我是如何到达那里的:

timeList=soup.findAll("span",{"class":"ci-details"})

我现在正试图尝试重复时代:

newTimes=timeList.findAll("span",{"\d\d\:\d\d"})

会导致此错误:

        Traceback (most recent call last):
    File "<pyshell#13>", line 1, in <module>
    newTimes=timeList.find("span",{"\d\d\:\d\d"})
    AttributeError: 'ResultSet' object has no attribute 'find'

(我应该使用这种正则表达式语法吗?[0-9][0-9]\:[0-9][0-9]

在我看来,我已经列出了一个列表,并将其列为一个较小的列表。我是对还是错?

我认为我的小名单会有findAll,findall甚至找到。

1 个答案:

答案 0 :(得分:1)

findAll是Beautiful Soup的Tag课程的一个属性。它不是list内置的属性。

因此,我们需要搜索ci_details列表的内容,并查看哪个<span class="ci-details">节点包含其内容与时间字符串匹配的<span> - "^\d\d:\d\d$"

此正则表达式使用^和$指定字符串匹配时没有任何前导或尾随字符。

#!/usr/bin/python3

from bs4 import BeautifulSoup, __version__
import re
import sys

print ("beautiful soup version: ", __version__)
print ("python version: ",  sys.version)
print

m = re.compile("^\d\d:\d\d$")

div = """
<div class="ci-details-container clearfix">
    <span class="ci-details">
        <i ng-class="::getCurrentLectureIcon()" class="icon-play-sign"></i>
        <span>02:29</span>
        <!-- ngIf: ::!elementData.content_summary -->
    </span>
</div>
"""

soup = BeautifulSoup(div)

ci_details = soup.findAll("span",{"class":"ci-details"})
print (ci_details)


timeList = []
for detail in ci_details:
    for span in detail.findAll("span"):
        if m.match(span.text):
            timeList.append(span.text)


print (timeList)

我得到以下输出:

beautiful soup version:  4.2.1
python version:  3.4.3 (default, Oct 14 2015, 20:28:29) 
[GCC 4.8.4]
[<span class="ci-details">
<i class="icon-play-sign" ng-class="::getCurrentLectureIcon()"></i>
<span>02:29</span>
<!-- ngIf: ::!elementData.content_summary -->
</span>]
['02:29']