在使用带有正则表达式的漂亮 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/