如何选择输入值

时间:2018-08-02 05:17:11

标签: beautifulsoup python-3.6

<div class="lang_selection"><input id="lang_0" name="language[]" 
value="0" type="checkbox"><label for="lang_0">English</label> 
</div>

<div class="lang_selection"><input id="lang_25" name="language[]" 
 value="25" type="checkbox"><label for="lang_25">Arabic</label> 
</div>

<div class="lang_selection"><input id="lang_22" name="language[]" 
 value="22" type="checkbox"><label for="lang_22">Portuguese- 
 Brazil</label></div>

<div class="lang_selection"><input id="lang_23" name="language[]" 
value="23" type="checkbox"><label for="lang_23">Bulgarian</label> 
</div>

<div class="lang_selection">
<input id="lang_19" name="language[]" value="19" type="checkbox"> 
<label for="lang_19">Czech</label>
</div>

我尝试了此代码

value = soup.find('input', {'name': 'language[]'}).get('value')

但给我错误:“ NoneType”对象不可下标

我想获取值为数字[0,25,22,23,19]的数组列表

2 个答案:

答案 0 :(得分:0)

您可能需要这个:

rangeLen = len(soup.findAll(attrs={"name" : "language[]"}))
language = soup.findAll(attrs={"name" : "language[]"})
valueList = list()

for i in range(rangeLen):
    valueList.append(int(language[i]['value']))

print(valueList)

输出:

[0, 25, 22, 23, 19]

答案 1 :(得分:0)

您可以使用CSS选择器,因此它将成为一个衬里:

print([int(i['value']) for i in soup.select(r'input[name^=language]') if 'value' in i.attrs])

打印:

[0, 25, 22, 23, 19]

input[name^=language]将选择所有<input>标签,其属性名称以language开头。