1

私はbeautifulsoupを使用していますが、find、findall、およびその他の機能を正しく使用する方法がわかりません...

私が持っている場合:

<div class="hey"></div>

使用:soup.find_all("div", class_="hey")

問題のdivを正しく見つけますが、次の場合はどうすればよいかわかりません:

<h3 id="me"></h3> # Find this one via "h3" and "id"

<li id="test1"></li># Find this one via "li" and "id"

<li custom="test2321"></li># Find this one via "li" and "custom"

<li id="test1" class="tester"></li> # Find this one via "li" and "class"

<ul class="here"></ul> # Find this one via "ul" and "class"

どんなアイデアでも大歓迎です:)

4

2 に答える 2

1

次のコードを見てください。

from bs4 import BeautifulSoup

html = """
<h3 id="me"></h3>
<li id="test1"></li>
<li custom="test2321"></li>
<li id="test1" class="tester"></li>
<ul class="here"></ul>
"""

soup = BeautifulSoup(html)

# This tells BS to look at all the h3 tags, and find the ones that have an ID of me
# This however should not be done because IDs are supposed to be unique, so
# soup.find_all(id="me") should be used
one = soup.find_all("h3", {"id": "me"})
print one

# Same as above, if something has an ID, just use the ID
two = soup.find_all("li", {"id": "test1"})  # ids should be unique
print two

# Tells BS to look at all the li tags and find the node with a custom attribute
three = soup.find_all("li", {"custom": "test2321"})
print three

# Again ID, should have been enough
four = soup.find_all("li", {"id": "test1", "class": "tester"})
print four

# Look at ul tags, and find the one with a class attribute of "here"
four = soup.find_all("ul", {"class": "here"})
print four

出力:

[<h3 id="me"></h3>]
[<li id="test1"></li>, <li class="tester" id="test1"></li>]
[<li custom="test2321"></li>]
[<li class="tester" id="test1"></li>]
[<ul class="here"></ul>]

これにより、必要なドキュメントが提供されます。

于 2013-10-19T16:52:39.423 に答える