chevron_left
Attribute Cookbook
0
0
0
new
Extracting attribute values in Beautiful Soup
Programming
chevron_rightPython
chevron_rightBeautiful Soup
chevron_rightCookbooks
chevron_rightAttribute Cookbook
schedule Jul 1, 2022
Last updated Python●Beautiful Soup
Tags tocTable of Contents
expand_more To extract attributes of elements in Beautiful Soup, use the [~]
notation. For instance, el["id"]
retrieves the value of the id
attribute.
Example
Consider the following HTML document:
my_html = """ <p id="alex" age="10">Alex</p> <p id="bob" age="20">Bob</p>"""soup = BeautifulSoup(my_html)
To extract the value of attributes id
and age
:
WARNING
An error will be thrown if the element does not contain the specified attribute
In order to avoid the error, you can check whether an element contains a specific attribute by calling has_attr(~)
first:
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
Ask a question or leave a feedback...
0
0
0
Enjoy our search