簡體   English   中英

我如何獲得一件物品,但前提是它是某個標簽的兄弟姐妹

[英]How do I get an item but only if is a sibiling of a certain tag

我有一個很長的 html 但這是一個片段:

<tr>
    <td data-bind="text:name, css: isActive() ? 'variable-active': 'variable-inactive'" class="variable-active">Vehicle</td>
    <td data-bind="text:value">Ford</td>
</tr>

<tr>
    <td data-bind="text:name, css: isActive() ? 'variable-active': 'variable-inactive'" class="variable-inactive">Model</td>
    <td data-bind="text:value">Focus</td>
</tr>

我想根據它是否為“變量活動”來獲取所有內容標簽,然后從下一個“td”標簽中獲取值。 在這種情況下,由於第二個 class 標記是“變量無效”,因此 output 應該是:

"Vehicle - Ford"

我設法根據“變量活動”獲取第一個標簽,但我無法從其他標簽中獲取第二個值。 這是我的代碼:

from bs4 import BeautifulSoup

with open ("html.html","r") as f:

doc = BeautifulSoup(f,"html.parser")

tag = doc.findAll("tr")[0]

print(tag.findAll(class_="variable-active")[0].contents[0]) #vehicle

tag.findNextSibling(class_="variable-active") # nothing

您想構建您的搜索有點不同:

tag = soup.findAll("tr")[0]

tag1 = tag.find(class_="variable-active")  # <-- use .find
tag2 = tag1.findNextSibling()              # <-- use tag1.findNextSibling() to find next sibling tag

print(tag1.text)                           # <-- use .text to get all text from tag
print(tag2.text)

印刷:

Vehicle
Ford

另一個使用 CSS 選擇器的版本:

data = soup.select(".variable-active, .variable-active + *")
print(" - ".join(d.text for d in data))

印刷:

Vehicle - Ford

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM