重温如何从网页提取时间

2024-04-25 14:58:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为我的工作做一些工作。我需要提取每个讲座的时间,这样我就可以把它们交给我的老板跟踪。我读过关于美的书。我已经开始上课了,时间是:

<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'

(我应该改用这个Regex语法吗?[0-9][0-9]\:[0-9][0-9]

在我看来,我已经列了一张单子,并把它缩小了。我是对的还是错的?你知道吗

我想我的小名单会有一个findAll,findAll甚至find。你知道吗


Tags: divcicontainer时间finddetailsng老板
1条回答
网友
1楼 · 发布于 2024-04-25 14:58:44

findAll是Beautiful Soup的Tag类的属性。它不是list内置的属性。你知道吗

因此,我们需要搜索ci\u详细信息列表的内容,并查看<span class="ci-details">节点中哪些包含内容与时间字符串匹配的<span>。你知道吗

这个正则表达式使用^和$来指定字符串匹配而不使用任何前导或尾随字符。你知道吗

#!/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']

相关问题 更多 >