Home > Enterprise >  beautifulsoup - how to get data from within self closing tag
beautifulsoup - how to get data from within self closing tag

Time:01-09

I'm trying to use beautifulsoup to retain the value "XXXXX" in the self closing html tag below (apologies if my terminology is incorrect)

Is this possible? All the questions I can find are around getting data out that is between div tags, rather than an attribute in a self closing tag.

<input name="nonce" type="hidden" value="XXXXX"/>

CodePudding user response:

Considering the text you need to parse is on the file variable, you can use the following code:

soup = BeautifulSoup(file, "html.parser")

X = soup.find('input').get('value')
print(X)

CodePudding user response:

I don't think it should make a difference that it's a self-closing tag in this case. The same methods should still be applicable. (Any of the methods in the comments should also work as an alternative.)

nonceInp = soup.select_one('input[name="nonce"]')
# nonceInp = soup.find('input', {'name': 'nonce'})

if nonceInp:
    nonceVal = nonceInp['value'] 
    # nonceVal = nonceInp.attrs['value'] 
    # nonceVal = nonceInp.get('value') 
    # nonceVal = nonceInp.attrs.get('value')
else: nonceVal = None # print('could not find an input named "nonce"')
  • Related