2012-06-26 39 views
54

我想根据它的名字打印属性值的属性值,举个例子的Python:BeautifulSoup - 获得基于的name属性

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

上面的代码给出​​,我相信这是因为BeatifulSoup使用了名称,所以它不能用作关键字参数。

回答

84

这很简单,使用下列 -

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

发表评论,如果你有什么不太清楚。

+0

我怎么能做到这一点,如果我想找到所有实例,也就是现在,soup.find( “元”,{ “名”: “城市”})['content']给出了第一个结果,但是说在汤中有另一行是 overflowname

+0

旧的问题,但这里有一个简单的解决方案,以防其他人来找它:'soup.findAll(“meta”,{“name”:“City”})['content']'。这将返回所有的事件。 –

6

theharshest的答案是最好的解决方案,但仅供参考您遇到的问题与美丽汤中的标签对象的行为如同Python字典一样。如果你在没有'name'属性的标签上访问标签['name'],你会得到一个KeyError。

12

最差的回答了这个问题,但这里是另一种做同样事情的方法。 另外,在你的例子中,你有大写的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 
+0

大小写不匹配可能是故意的,因为默认情况下,BeautifulSoup将标签转换为小写。在这种情况下: BeautifulSoup('')返回 tuckermi

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 
2

以下工作:

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