繁体   English   中英

如何使用BeautifulSoup匹配仅包含所述类而不包含任何其他类的标签?

[英]How do I match a tag containing only the stated class, not any others, using BeautifulSoup?

有没有一种方法可以使用BeautifulSoup将标记与指定的class属性匹配,而不与指定的class属性匹配? 例如,在以下简单的HTML中:

<html>
 <head>
  <title>
   Title here
  </title>
 </head>
 <body>
  <div class="one two">
   some content here
  </div>
  <div class="two">
   more content here
  </div>
 </body>
</html>

是否有可能只匹配divclass="two" ,但不能匹配divclass="one two" 除非我缺少任何内容,否则文档的那部分不会给我任何想法。 这是我当前正在使用的代码:

from bs4 import BeautifulSoup

html = '''
<html>
 <head>
  <title>
   Title here
  </title>
 </head>
 <body>
  <div class="one two">
   should not be matched
  </div>
  <div class="two">
   this should be matched
  </div>
 </body>
</html>
'''

soup = BeautifulSoup(html)
div_two = soup.find("div", "two")
print(div_two.contents[0].strip())

我试图让它打印this should be matched而不是should not be matched

编辑:在这个简单的示例中,我知道类的唯一选项是"one two""two" ,但是在生产代码中,我只会知道我要匹配的类将是"two" 除了"two"之外,其他标签可能还具有大量其他类别,这可能是未知的。

与此相关的是,阅读版本4文档也很有帮助,而不是我之前链接的版本3。

尝试:

divs = soup.findAll('div', class="two")

for div in divs:
    if div['class'] == ['two']:
        pass # handle class="two"
    else:
        pass # handle other cases, including but not limited to "one two"

希望下面的代码对您有所帮助。 虽然我没有尝试过。

soup.find("div", { "class" : "two" })

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM