LoginSignup
4
1

More than 3 years have passed since last update.

[Python]BeautifulSoupでname属性を指定して要素を取得する

Posted at

BeautifulSoupでhtml要素を取得する際にname属性を指定したい時のお話。

基本的なfind

# 取得例
source = soup.find('div', class_='hogehoge')

基本はこのような形でsoup.find('タグ名', 属性名='値')と指定して取得する。
ですが、name属性でこの記述をするとエラーになる。

# 取得例
source = soup.find('input', name='hogehoge', type='hidden')
実行結果
TypeError: find() got multiple values for keyword argument 'name'

これはBeautifulSoupのfindメソッド内で既にnameという引数を定義している為エラーとなるらしい。

name属性を指定する際の記述

source = soup.find('input', attrs={'name': 'hogehoge', 'type': 'hidden'})

attrsという引数に辞書型で値を渡してあげるとname属性を指定する事が出来るみたいなのでこれで指定する。

source = soup.find('input', {'name': 'hogehoge', 'type': 'hidden'})

引数を省略しても同じ結果が得られるので好きな方を選びましょう。

参考リンク

Parameters for find function
Python:BeautifulSoup-名前属性に基づいて属性値を取得します

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1