Python Beautifulsoup查找正确的标记

2024-09-30 18:13:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我在想如何抓取我需要的特定标签时遇到了问题。你知道吗

<div class="meaning"><span class="hinshi">[名]</span><span class="hinshi">(スル)</span></div>, <div class="meaning"><b>1</b> 今まで経験してきた仕事・身分・地位・学業などの事柄。履歴。「―を偽る」</div>,

现在我有它,所以它可以找到所有的意义类,但我需要缩小范围,甚至进一步从这个得到我想要的。以上就是一个例子。我只需要抓住

"<div class="meaning"><b>". 

忽略所有的“欣士”课程。你知道吗

编辑:它似乎显示的数字,我猜是什么,但我需要它旁边的文字。有什么想法吗?你知道吗


Tags: div编辑标签class例子课程意义span
3条回答

你可以这样做

for s in soup.findAll("div {class:meaning}"):
    for b in s.findAll("b"):
     #   b.getText("<b>")

在“#”行中,您应该根据结果来修复它。你知道吗

您可以尝试使用.select函数,该函数采用CSS选择器:

soup.select('.meaning b')

您可以使用find方法的关键字参数来查找特定属性。在您的例子中,您需要匹配class_关键字。关于class_关键字,请参见documentation。你知道吗

假设您希望筛选不包含“hinshi”类的任何子级的元素,可以尝试以下操作:

soup = BeautifulSoup(data)
potential_matches = soup.find_all(class_="meaning")

matches = []
for match in potential_matches:
  bad_children = match.find_all(class_="hinshi")
  if not bad_children:
    matches.append(match)

return matches

如果您愿意,您可以将其缩短一点,例如:

matches = soup.find_all(class_="meaning")
return [x for x in matches if not x.find_all(class_="hinshi")]

或者,根据您的Python版本,即2.x:

matches = soup.find_all(class_="meaning")
return filter(matches, lambda x: not x.find_all(class_="hinshi"))

编辑:如果要在示例中查找数字旁边的外来字符,应首先删除b元素,然后使用get_text方法。例如

# Assuming `element` is one of the matches from above
element.find('b').extract()
print(element.get_text())

相关问题 更多 >