Python beautifulsoup - 获取输入值

时间:2012-07-27 15:46:15

标签: python beautifulsoup

我有很多这样的表格行:

<tr>
    <td>100</td>
    <td>200</td>
    <td><input type="radio" value="123599"></td>
</tr>

迭代:

table = BeautifulSoup(response).find(id="sometable") # Make soup.

for row in table.find_all("tr")[1:]: # Find rows.
    cells = row.find_all("td") # Find cells.

    points = int(cells[0].get_text())
    gold = int(cells[1].get_text())
    id = cells[2].input['value']

    print id

错误:

File "./script.py", line XX, in <module>
id = cells[2].input['value']
TypeError: 'NoneType' object has no attribute '__getitem__'

我如何获得输入值?我不想使用正则表达式。

2 个答案:

答案 0 :(得分:40)

soup = BeautifulSoup(html)
try:
    value = soup.find('input', {'id': 'xyz'}).get('value')
except:
    pass

答案 1 :(得分:-2)

您想要找到&lt; input&gt;单元格内部的元素,所以你应该在单元格上使用find / find_all,如下所示:

cells[2].find('input')['value']