I’m pretty new to Python and even more new to lxml, but what I’m trying to do seems really simple but I can’t figure out what I’m doing wrong.
I have this code with the goal of feeding a list of values (list object ISBN) to lxml to submit to a search field:
for i in ISBN:
page.forms[0].fields['_nkw'] = ISBN[i]
blah blah blah
I get this error after running:
Traceback (most recent call last):
page.forms[0].fields['_nkw'] = ISBN[i]
TypeError: list indices must be integers, not str
Obviously there has to be a way to iterate through a list of values to feed to a form, but clearly I don’t know it 🙂
EDIT: FYI the code works fine when replacing ISBN[i] with hard input.
EDIT 2: contents of ISBN list object as requested:
['9781608319053', '9780321558237', '9781932735413', '9781416059516', '9781437708257', '9780781780582', '9781437701517', '9780323065801', '9780890420256', '9780323079334', '9781599417042', '9780781771535', '9781416031215', '9780312601430', '9780781775250', '9781591263333', '9780071748896', '9780133669510', '9781416045748', '9780781771566', '9781437728019', '9780323065849', '9781416066675', '9780735579965', '9780323078917', '9781437735826', '9781603595681', '9780321696724', '9780321558145', '9781933107981', '9780138024611']
The trouble is with your loop over and use of the ISBN variable. You don’t need to be indexing it during your assignment, since
ialready holds an element of the list, extracted as part of the loop. You’re getting an exception because you can’t index a list with a string, even if that string came out of the list itself.Instead, use
page.forms[0].fields['_nkw'] = i.Or if you need the index into the ISBN list for later code that you haven’t shown, keep the assignment as it is, and change the loop declaration to: