2017-05-22 8 views
1

入力フィールドの名前属性(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()?

入力フィールドのname属性を印刷するためのコードと何が問題なのですか?

+0

エラーメッセージはここではっきりしていますね。 –

答えて

2

find_all()メソッドをfind()に置き換え、属性名を使用して値を取得してください。それはdictionaryです。

form = soup.find('form') 
inputs = form.find('input', type='text') 
print(inputs['name']) 

別の方法:

form = soup.find('form') 
inputs = form.find('input', type='text').get('name') 
print(inputs) 

第二の方法は、より安全です。 name属性がない場合はNoneを返しますが、第1の方法ではKeyErrorとなります。

+0

入力フィールドがtype = textで、type = submitではない場合にのみ、名前を具体的に見つける方法。 –

+0

@MaccenWrightコードを更新しました。それを見てみましょう。 –

0
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 

あなただけの最初または最後のタグを取得することを確認している場合は、以下のようにそれのインデックスでリストおよびアクセス要素として入力を扱うことができます属性:

inputs[1].get('name') 

、あなたは常に最初の要素にアクセスする必要がある場合@MDによって提供されるステップに従うだけの方が良い。 Khairul Basar

関連する問題