Skip to main content
 首页 » 编程设计

python之获取使用 lxml 设置的单选按钮值的最佳方法是什么

2025年05月04日7bhlsheji

例如我有以下单选按钮:

<input type="radio" name="hand"  id='hand_left' checked value="L">  
  <label for='hand_left'>Left</label> 
 
<input type="radio" name="hand" id='hand_right' value="R">  
  <label for='hand_right'>Right</label> 

并有如下解析代码:

import lxml.html as lh 
 
doc=lh.parse(response) # response is the response of  
                       # http post that returns the above html 
 
for el in doc.iter('input'): 
   if el.name == 'hand': 
     print el 

打印出两个 InputElements,但 lxml 只为选中的返回一个值,并为未选中的返回 None(根据 lxml 文档)。无论选中哪个,我都想获取每个潜在值。

<InputElement 8715f8c name='hand' type='radio'> 
<InputElement 8715f8f name='hand' type='radio'> 

请您参考如下方法:

您可以使用 el.attrib['value'] 而不是 el.value