python - 使用带有正则表达式的美丽汤提取时间

标签 python beautifulsoup

在使用带有正则表达式的漂亮 Soup 时,我需要帮助来获得正确的语法

我使用下面的代码只抓取时间。时间位于包含一个段落的 DIV 中。 DIV 及其内容如下所示:

<div class="details"> 
    <p> $25 
    <br>
     8/23<br>
     7:00 pm 
     </p>                             
</div>

代码:

from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen('https://place_holder/')
bs = BeautifulSoup(html.read(), 'html.parser')
for time_date in bs.find_all("div", {"class": "details"}):
    print(time_date.text)

当我运行上面的代码时,我得到了以下结果。

$25 
8/23
7:00 pm

因为我只想提取时间(晚上 7:00),所以我想使用正则表达式来执行此操作。我无法提供有效的正确语法。我希望有人能帮助我。

最佳答案

这里不需要正则表达式。 BeautifulSoup 可以为您提供所需的数据。只需访问 <p> 的最后一个元素使用 .contents[-1] 标记.

for time_date in bs.find_all("div", {"class": "details"}):
    print(time_date.p.contents[-1].strip())
# 7:00 pm

.contents一个标签看起来像这样:

[' $25 \n    ', <br/>, '\n     8/23', <br/>, '\n     7:00 pm \n     ']

如果你需要使用正则表达式,你可以使用这个:

for time_date in bs.find_all("div", {"class": "details"}):
    print(re.findall(r'\d+:\d+ [ap]m', time_date.text)[0])

关于python - 使用带有正则表达式的美丽汤提取时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57505832/

相关文章:

python - tensorflow : How do i find my output node in my Tensorflow trained model?

python - 如何在 Keras 中正确实现自定义事件正则化器?

python - 使用 BeautifulSoup 拆分 HTML 文档

python - BeautifulSoup 在某些下载请求中拾取 div 对象,但在其他下载请求中拾取 div 对象

python - 调用后python中的声明函数

python - 在 Amazon AWS 上使用 python 从另一台 EC2 服务器上使用 HBase EMR

python - 将父前缀号码扩展到给定的子号码

python - (Python 3, BeautifulSoup 4) - 在 Div 中抓取分页

python - Beautifulsoup:当我尝试使用 Beautifulsoup4 访问 soup.head.next_sibling 值时换行

beautifulsoup - Beautiful Soup - 如何获得 href