21
votes

I've got many table rows like this:

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

Iterate with:

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

Error:

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

How can I get input value? I don't want to use regexp.

2
It looks like for at least one of your rows, there is no input tag in the third cell. Please provide the whole markup, or catch the error and have it print the row. - Will
BeautifulSoup is notoriously fragile. Better use lxml or lxml.html. - Andreas Jung
@Will: You're correct, I miss that. There's a one row without input tag. Thank you very much. - Mateusz Jagiełło

2 Answers

53
votes
soup = BeautifulSoup(html)
try:
    value = soup.find('input', {'id': 'xyz'}).get('value')
except Exception as e:
    print("Got unhandled exception %s" % str(e))
-2
votes

You want to find the <input> element inside the cell, so you should use find/find_all on the cell like this:

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