gpt4 book ai didi

python - 查找所有 div 标签 find class = "post-"后面跟着一些数字?

转载 作者:行者123 更新时间:2023-12-01 03:44:42 26 4
gpt4 key购买 nike

我想找到所有带有 class = "post-some number some text "的 div 标签有多个 div 标签,例如

<div class="post-3562 some text">
<div class="post-some text">
<div class="post-some text">
<div class="post-1324 some text">
<div class="post-4540 some text">
<div class="post-some text">
<div class="post-1122 some text">

我只想获取那些带有 class="post-some number"的 div 标签

目前我已经写了这个:

allPostsDiv = soup.find_all("div", class_= "post")

有办法实现我想做的事情吗?使用正则表达式可能会有帮助吗?任何帮助将不胜感激。

最佳答案

您可以传入正则表达式作为 class_ 参数的值,如下所示:

soup.find_all(name='div', class_=re.compile(r'^post-\d+$'))

完整程序:

from bs4 import BeautifulSoup
import re

soup = BeautifulSoup('''
<root>
<div class="post-3562 some text"/>
<xdiv class="post-9999 some text"/>
<div class="post-some text"/>
<div class="post-some text"/>
<div class="post-1324some text"/>
<div class="some post-4540 text"/>
<div class="post-some text"/>
<div class="some text post-1122"/>
</root>''', 'html.parser')

for div in soup.find_all(name='div', class_=re.compile(r'^post-\d+$')):
print div

结果:

<div class="post-3562 some text"></div>
<div class="some post-4540 text"></div>
<div class="some text post-1122"></div>

关于python - 查找所有 div 标签 find class = "post-"后面跟着一些数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39103486/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com