Here's html code I'm working on.
<div class="input-group m-b">
<span class="input-group-addon">
$
</span>
<input class="form-text form-control input-lg-3" disabled="disabled"
groupfields="$" id="edit-transfer--3" maxlength="128"
name="transfer_d" size="60" type="text" value="71"/>
</div>
What I want is to get "71" which is the value of a "value" tag
I've tried
elem = soup.find('input', attrs={'id':'edit-transfer--3'})
print(elem)
and gives
<input class="form-text form-control input-lg-3" disabled="disabled" groupfields="$" id="edit-transfer--3" maxlength="128" name="transfer_d" size="60" type="text" value="71"/>
and I'm stuck
print(elem.find('value')
gives me None
and
print(elemd.find('value').get_text())
gives me an error
AttributeError: 'NoneType' object has no attribute 'get_text'
How can I extract the value from the tag?
Try this:
from bs4 import BeautifulSoup
html = '''<div class="input-group m-b">
<span class="input-group-addon">
$
</span>
<input class="form-text form-control input-lg-3" disabled="disabled"
groupfields="$" id="edit-transfer--3" maxlength="128"
name="transfer_d" size="60" type="text" value="71"/>
</div>'''
soup = BeautifulSoup(html, "html.parser")
elem = soup.find('input', attrs={'id':'edit-transfer--3'})
print(elem['value'])
returns
71
The find
method is used to find child elements from the parent. Since value is an attribute and there's no element tag called value, None is returned.
The get_text
method will only extract the innerText
of the element. Since the previous find
returned None, it throws the error.
To get a specific attribute you need to use square brackets.