在元素中查找元素的漂亮汤简单python错误? [英] Beautiful soup simple python error with finding elements within elements?

查看:97
本文介绍了在元素中查找元素的漂亮汤简单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_allcontainer中获取所有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

这篇关于在元素中查找元素的漂亮汤简单python错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆