在元素中查找元素的漂亮汤简单python错误?
我遇到了一个BS4错误,该错误没有给出任何解释,至少不是我所理解的,有人可以帮助我知道它的含义吗? 这是代码:
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")
这是错误:
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
如果您注意到#out代码会给出完全相同的错误
if you notice the # out code it gives the exact same error
containerlv2
是标签对象,它没有6作为键,因此得到KeyError: 6
containerlv2
is a tag object, and it does not have 6 as key, therefore you got KeyError: 6
如果您要在第7个tr
标签中搜索div
标签,则正确的方法应该是:
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')
首先,您使用find_all
在container
中获取所有tr
标记并将它们放入列表containerlv2
中,然后在containerlv2
的第7个标记中搜索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