Python:BeautifulSoup - 根据name属性获取属性值

时间:2012-06-26 10:29:43

标签: python beautifulsoup

我想根据名称打印属性值,例如

<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',我相信这是因为BeatifulSoup使用了name,所以它不能用作关键字参数。

7 个答案:

答案 0 :(得分:124)

这很简单,请使用以下内容 -

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

如果有任何不明确的地方,请发表评论。

答案 1 :(得分:22)

theharshest 回答了这个问题,但这是另一种做同样事情的方法。 此外,在您的示例中,您有大写的NAME,在您的代码中,您有小写的名称。

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

答案 2 :(得分:8)

以下作品:

from bs4 import BeautifulSoup

soup = BeautifulSoup('<META NAME="City" content="Austin">', 'html.parser')

metas = soup.find_all("meta")

for meta in metas:
    print meta.attrs['content'], meta.attrs['name']

答案 3 :(得分:7)

theharshest的答案是最好的解决方案,但是你遇到的问题仅与美丽汤中的Tag对象就像Python字典这样的事实有关。如果您在没有'name'属性的标记上访问标记['name'],您将获得KeyError。

答案 4 :(得分:5)

晚会结束6年但我一直在寻找如何提取 html元素的标签 属性值,因此适用于:

<span property="addressLocality">Ayr</span>

我想要“addressLocality”。我一直被引导到这里,但答案并没有真正解决我的问题。

我最终是如何做到的:

>>> from bs4 import BeautifulSoup as bs

>>> soup = bs('<span property="addressLocality">Ayr</span>', 'html.parser')
>>> my_attributes = soup.find().attrs
>>> my_attributes
{u'property': u'addressLocality'}

因为它是一个词典,你也可以使用keys和'值'

>>> my_attributes.keys()
[u'property']
>>> my_attributes.values()
[u'addressLocality']

希望它可以帮助别人!

答案 5 :(得分:1)

{
    "id": "2",
    "email": "ckelly@gmail.com",
    "isAdmin": false
}

答案 6 :(得分:0)

也可以试试这个解决方案:

查找以表格

的范围写入的值

<强> htmlContent

<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