Reputation:
I'm trying to find the name attribute of the input field where type = name.
import bs4 as bs
import urllib.request
import requests
import webbrowser
import urllib.parse
url = "http://demo.testfire.net/default.aspx"
sauce = urllib.request.urlopen(url).read()
soup = bs.BeautifulSoup(sauce,"html.parser")
form = soup.find('form')
inputs = form.find_all('input')
print(inputs.name)
Error: ResultSet object has no attribute 'name'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?
What's wrong with the code to print the name attribute of the input field?
Upvotes: 0
Views: 1527
Reputation: 4213
import bs4 as bs
import requests
url = "http://demo.testfire.net/default.aspx"
sauce = requests.get(url).content # also okay to use urllib.urlopen(url).read() by importing urllib
soup = bs.BeautifulSoup(sauce,"html.parser")
form = soup.find('form')
inputs = form.find_all('input') # here you get single or multiple 'bs4.element.Tag' in 'bs4.element.ResultSet'
# hence you need to iterate all result as below
for elements in inputs:
print(elements.get('name')) # you will get txtSearch and None
if you are sure to get only first or last tag attribute you can treat inputs as list and access element by it's index as below:
inputs[1].get('name')
and if you always need to access first element only better to follow steps provided by @MD. Khairul Basar
Upvotes: 1
Reputation: 5110
Replace the find_all()
method with find()
and and then just use the attribute name to get the value. It's a dictionary
.
form = soup.find('form')
inputs = form.find('input', type='text')
print(inputs['name'])
Another way:
form = soup.find('form')
inputs = form.find('input', type='text').get('name')
print(inputs)
The 2nd way is safer. Because if there is no name
attribute it will return None
but in the 1st way it will give KeyError
.
Upvotes: 3