2012-06-26 12 views
54

ich einen Attributwert drucken möchten, basierend auf seinen Namen, nehmen Sie zum BeispielPython: BeautifulSoup - einen Attributwert erhalten basierend auf dem Namen Attribut

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

Ich möchte so etwas wie dieses

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

Der obige Code geben eine KeyError: 'name', ich glaube, das ist, weil Name von Beatifulsoup verwendet wird, so dass es nicht als ein Schlüsselwort Argument verwendet werden kann.

Antwort

84

Es ist ziemlich einfach, verwenden Sie die folgende -

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

Hinterlassen Sie einen Kommentar, wenn etwas nicht klar ist.

+0

, wie ich das tun kann, wenn ich alle Instanzen finden will, also gerade jetzt, soup.find ("meta", { "name": "Stadt"}) ['Inhalt'] gibt das erste Ergebnis, aber es gibt eine andere Zeile in der Suppe, die war. Wie könnte ich den Code ändern, um "Austin" und "San Francisco" zu erhalten? – overflowname

+0

Alte Frage, aber hier ist eine einfache Lösung für den Fall, dass jemand anderes danach sucht: 'sup.findAll (" meta ", {" name ":" Stadt "}) ['content']' '. Dies wird alle Vorkommen zurückgeben. –

6

Die Antwort von theharshest ist die beste Lösung, aber das Problem, auf das Sie gestoßen sind, hängt damit zusammen, dass ein Tag-Objekt in Beautiful Soup wie ein Python-Wörterbuch funktioniert. Wenn Sie auf ein Tag ['name'] auf einem Tag zugreifen, das kein Attribut 'name' hat, erhalten Sie einen KeyError.

12

Thesharest beantwortet die Frage, aber hier ist eine andere Möglichkeit, das Gleiche zu tun. In Ihrem Beispiel haben Sie NAME in Großbuchstaben und in Ihrem Code haben Sie einen Namen in Kleinbuchstaben.

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

Die Nichtübereinstimmung in Fall ist wahrscheinlich beabsichtigt, weil BeautifulSoup standardmäßig Tags in Kleinbuchstaben konvertiert. In diesem Fall: BeautifulSoup ('') gibt zurück – tuckermi

0

Man kann auch diese Lösung versuchen:

den Wert zu finden, die

htmlcontent in Spannweite von Tabelle geschrieben


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


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

Die folgenden Werke:

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