简体   繁体   English

我如何获得一件物品,但前提是它是某个标签的兄弟姐妹

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

I have a long html but here's a fragment:我有一个很长的 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>

I want to get all the content tags based on if it is "variable-active", and then get the value from the next 'td' tag.我想根据它是否为“变量活动”来获取所有内容标签,然后从下一个“td”标签中获取值。 In this case, as the second class tag is "variable-inactive", the output should be:在这种情况下,由于第二个 class 标记是“变量无效”,因此 output 应该是:

"Vehicle - Ford"

I managed to get the first tags based on the "variable-active" but I can't get the second values from the other tags.我设法根据“变量活动”获取第一个标签,但我无法从其他标签中获取第二个值。 This is my code:这是我的代码:

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

You want to structure your search a little bit different:您想构建您的搜索有点不同:

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)

Prints:印刷:

Vehicle
Ford

Another version using CSS selectors:另一个使用 CSS 选择器的版本:

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

Prints:印刷:

Vehicle - Ford

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何仅获取 HTML 树的一部分,该部分位于带有特定字符串 BeautifulSoup 的特定标签之上? - How do I get only the part of an HTML tree which is above a certain tag with certain string BeautifulSoup? 在 Python 中,如何在使用嵌套 for 循环时跳过列表中的项目,但仅限于某些条件? - In Python, how do I skip an item in a list when using nested for loops, but only in certain conditions? 如何制作仅在for循环中出现的elif命令才能为列表中某项的某些实例注册? - How do I make an elif command which occurs in a for loop only register for certain instances of an item within the list? 一旦我得到超过特定条件限制的项目,我如何停止列表理解 - How do I stop list comprehension once i get an item above certain condition limit 仅当项目符合python中的某些规则时,我才能追加项目 - How can i append a an item only if it meets certain rules in python 如何计算 ndarray 中某个项目的出现次数? - How do I count the occurrence of a certain item in an ndarray? 如何检查Python NLTK中的某个标签? - How do I check for a certain tag in Python NLTK? 如何从某个输入中获得某个响应 - How do I get a certain response from a certain input 我如何获得下一个标签 - how do i get the next tag 如何获得某些标签值 - How to get certain Tag Values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM