2012-06-26 40 views
54

Tôi muốn in một giá trị thuộc tính dựa vào tên của nó, lấy ví dụPython: BeautifulSoup - nhận được một giá trị thuộc tính dựa trên thuộc tính tên

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

tôi muốn làm một cái gì đó như thế này

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

Đoạn mã trên cho một số KeyError: 'name', tôi tin rằng đây là vì tên được sử dụng bởi BeatifulSoup nên nó không thể được sử dụng làm đối số từ khóa.

Trả lời

84

Nó khá đơn giản, sử dụng như sau -

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

Leave a comment nếu bất cứ điều gì không rõ ràng.

+0

làm thế nào tôi có thể làm điều này nếu tôi muốn tìm tất cả các trường hợp, tức là ngay bây giờ, soup.find ("meta", { "tên": "Thành phố"}) ['nội dung'] cho kết quả đầu tiên, nhưng nói có một dòng khác trong món súp overflowname

+0

Câu hỏi cũ, nhưng đây là giải pháp đơn giản trong trường hợp bất kỳ ai khác tìm kiếm: 'soup.findAll (" meta ", {" name ":" City "}) ['content']'. Điều này sẽ trả về tất cả các lần xuất hiện. –

6

câu trả lời của theharshest là giải pháp tốt nhất, nhưng FYI vấn đề bạn gặp phải liên quan đến thực tế là đối tượng Thẻ trong Beautiful Soup hoạt động như một từ điển Python. Nếu bạn truy cập thẻ ['name'] trên thẻ không có thuộc tính 'name', bạn sẽ nhận được KeyError.

12

theharshest đã trả lời câu hỏi nhưng đây là một cách khác để thực hiện tương tự. Ngoài ra, trong ví dụ của bạn, bạn có NAME ở dạng mũ và trong mã của bạn, bạn có tên bằng chữ thường.

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

Sự không phù hợp trong trường hợp có thể là cố ý vì BeautifulSoup chuyển đổi thẻ thành chữ thường theo mặc định. Trong trường hợp này: BeautifulSoup ('') trả về tuckermi

0

Một cũng có thể thử giải pháp này:

Để tìm giá trị, được viết bằng khoảng thời gian bàn

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> 

mã 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

Các công trình sau đây:

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'] 
Các vấn đề liên quan