2012-06-26 42 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']