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']
Приведенный выше код дает KeyError: 'name'
, я считаю, что это потому, что имя используется BeatifulSoup, поэтому его нельзя использовать в качестве аргумента ключевого слова.
Ответы
Ответ 1
Это довольно просто, используйте следующее -
>>> 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'
Оставить комментарий, если что-то неясно.
Ответ 2
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
Ответ 3
самый лучший ответ - лучшее решение, но FYI проблема, с которой вы столкнулись, связана с тем, что объект Tag в Beautiful Soup действует как словарь Python. Если вы используете тег ['name'] в теге, который не имеет атрибута 'name', вы получите KeyError.
Ответ 4
Следующие работы:
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']
Ответ 5
Можно также попробовать это решение:
Чтобы найти значение, которое написано в диапазоне таблицы
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