112

たとえば、名前に基づいて属性値を出力したい

<META NAME="City" content="Austin">

私はこのようなことをしたい

soup = BeautifulSoup(f)  # f is some HTML containing the above meta tag
for meta_tag in soup("meta"):
    if meta_tag["name"] == "City":
        print(meta_tag["content"])

上記のコードKeyError: 'name'は を返します。これは、 name が BeatifulSoup によって使用されるため、キーワード引数として使用できないためだと思います。

4

7 に答える 7

183

それは非常に簡単です、次を使用してください-

>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('<META NAME="City" content="Austin">')
>>> soup.find("meta", {"name":"City"})
<meta name="City" content="Austin" />
>>> soup.find("meta", {"name":"City"})['content']
u'Austin'

不明な点があればコメントを残してください。

于 2012-06-26T10:51:26.533 に答える
34

theharsestは質問に答えましたが、同じことを行う別の方法があります。また、あなたの例では名前が大文字で、コードでは名前が小文字になっています。

s = '<div class="question" id="get attrs" name="python" x="something">Hello World</div>'
soup = BeautifulSoup(s)

attributes_dictionary = soup.find('div').attrs
print attributes_dictionary
# prints: {'id': 'get attrs', 'x': 'something', 'class': ['question'], 'name': 'python'}

print attributes_dictionary['class'][0]
# prints: question

print soup.find('div').get_text()
# prints: Hello World
于 2014-03-12T17:56:56.417 に答える
8

theharsest の答えが最善の解決策ですが、参考までに、発生していた問題は、Beautiful Soup の Tag オブジェクトが Python 辞書のように機能するという事実に関係しています。'name' 属性を持たないタグで tag['name'] にアクセスすると、KeyError が返されます。

于 2012-06-26T12:18:24.797 に答える
1

この解決策を試すこともできます:

テーブルのスパンに書かれている値を見つけるには

htmlコンテンツ


<table>
    <tr>
        <th>
            ID
        </th>
        <th>
            Name
        </th>
    </tr>


    <tr>
        <td>
            <span name="spanId" class="spanclass">ID123</span>
        </td>

        <td>
            <span>Bonny</span>
        </td>
    </tr>
</table>

Python コード


soup = BeautifulSoup(htmlContent, "lxml")
soup.prettify()

tables = soup.find_all("table")

for table in tables:
   storeValueRows = table.find_all("tr")
   thValue = storeValueRows[0].find_all("th")[0].string

   if (thValue == "ID"): # with this condition I am verifying that this html is correct, that I wanted.
      value = storeValueRows[1].find_all("span")[0].string
      value = value.strip()

      # storeValueRows[1] will represent <tr> tag of table located at first index and find_all("span")[0] will give me <span> tag and '.string' will give me value

      # value.strip() - will remove space from start and end of the string.

     # find using attribute :

     value = storeValueRows[1].find("span", {"name":"spanId"})['class']
     print value
     # this will print spanclass
于 2016-10-20T05:38:11.177 に答える