问题
I've come across a BS4 error that gives no explanation, at least not one I understand, could someone help me know what it means? here is the code:
soup = BeautifulSoup(browser.page_source, "html.parser")
soup.prettify()
container = soup.find('table', {'id': 'RmvMainTable'})
containerlv2 = container.find('tr')
# related_files = containerlv2[6].find('div')
# print(related_files)
for re_file in containerlv2[6].find('div'):
print("lol")
and here is the error:
Traceback (most recent call last):
File "/home/user/Python projects/test/test3.py", line 162, in <module>
for re_file in containerlv2[6].find('div'):
File "/usr/lib/python3/dist-packages/bs4/element.py", line 958, in __getitem__
return self.attrs[key]
KeyError: 6
if you notice the # out code it gives the exact same error
回答1:
containerlv2 is a tag object, and it does not have 6 as key, therefore you got KeyError: 6
If you are trying to search for div tag in the 7th tr tag, the correct way should be:
containerlv2 = container.find_all('tr')
related_files = containerlv2[6].find('div')
First you use find_all to get all tr tags in container and put them into a list containerlv2, and then you search for div in the 7th tag of containerlv2
回答2:
containerlv2 = container.find('tr')
this will return a tag object, and you index a tag object like this
containerlv2[6]
来源:https://stackoverflow.com/questions/41007728/beautiful-soup-simple-python-error-with-finding-elements-within-elements