2

BeautifulSoupを使用して、指定された属性などではなく、指定された属性のみでタグを一致させる方法はありますか? たとえば、次の単純な HTML では:classclass

<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>

withのみを一致させ、divwithを一致さclass="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"or"two"であることを知っていますが、実稼働コードでは、一致させたいものに class があることしかわかりません"two"。他のタグには、 に加えて、未知の可能性がある多数の他のクラスが"two"ある可能性があります。

関連して、以前にリンクしたバージョン 3 ではなく、バージョン4のドキュメントを読むことも役立ちます。

4

2 に答える 2

4

試す:

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"
于 2012-07-16T16:59:45.540 に答える
0

以下のコードがお役に立てば幸いです。私はこれを試していませんが。

soup.find("div", { "class" : "two" })
于 2012-07-16T17:01:16.353 に答える