亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 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 關注
  • 225 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號