为了账号安全,请及时绑定邮箱和手机立即绑定

使用 BeatifulSoup 选择其他两个标签之间的所有标签

使用 BeatifulSoup 选择其他两个标签之间的所有标签

白衣非少年 2021-08-14 21:20:13
我想提取包含在两个标签之间的给定标签的所有实例。目前我正在与 BeautifulSoup 合作。您可以在下面找到一个示例:<p class='x' id = '1'> some content 1 <p><p class='y' id = 'a'> some content a <p><p class='y' id = 'b'> some content b <p><p class='y' id = 'c'> some content c <p><p class='potentially some other class'> <p><p class='x' id = '2'> some content 2 <p><p class='y' id = 'd'> some content d <p><p class='y' id = 'e'> some content e <p><p class='y' id = 'f'> some content f <p>我有兴趣在两个标签“x”之间选择“y”类的所有实例,它们也具有不同的 id。关于具体示例,我想选择所有带有 class = 'y' 的 p,然后检索文本。我最终想要的输出是:“某些内容 a”、“某些内容 b”和“某些内容 c”。我尝试使用 findAllNext 方法,但这给了我“一些内容 a”、“一些内容 b”、“一些内容 c”和“一些内容 d”、“一些内容 e”、“一些内容 f”。下面是我的代码par = BeautifulSoup(HTML_CODE).content, 'lxml') loc = par.find('p', class_ = 'x', id ='1')desired = loc.findAllNext('p', class_ = 'y')有什么方法可以避免选择出现在 class='x' 和 id = '2' 标签之后的 class = 'y' 实例吗?
查看完整描述

1 回答

?
繁花如伊

TA贡献2012条经验 获得超12个赞

你可以从你想要的地方开始迭代并结束它,直到找到一些标记完成。


from bs4 import BeautifulSoup


html = """


<p class='x' id = '1'> some content 1 </p>

<p class='y' id = 'a'> some content a </p>

<p class='y' id = 'b'> some content b </p>

<p class='y' id = 'c'> some content c </p>

<p class='potentially some other class1'> potentially some other class 1 </p>

<p class='potentially some other class2'> potentially some other class 2</p>

<p class='potentially some other class3'> potentially some other class 3 </p>

<p class='x' id = '2'> some content 2 </p>

<p class='y' id = 'd'> some content d </p>

<p class='y' id = 'e'> some content e </p>

<p class='y' id = 'f'> some content f </p>

"""


soup = BeautifulSoup(html,"lxml")

start = soup.find("p",class_="y",id="c")

end = soup.find("p",class_="x",id="2")

def next_ele(ele,result=[]):

    row = ele.find_next("p")

    if not row or row == end:

        return result

    result.append(row)

    return next_ele(row,result)


print(next_ele(start))


查看完整回答
反对 回复 2021-08-14
  • 1 回答
  • 0 关注
  • 202 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号