【问题标题】:Beautiful soup simple python error with finding elements within elements?美丽的汤简单的python错误,在元素中查找元素?
【发布时间】:2016-12-07 01:07:56
【问题描述】:

我遇到了一个 BS4 错误,它没有给出任何解释,至少我无法理解,有人可以帮我知道它的含义吗? 这是代码:

    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 代码,它会给出完全相同的错误

【问题讨论】:

    标签: python-3.x beautifulsoup runtime-error


    【解决方案1】:

    containerlv2是一个标签对象,它没有6作为key,所以你得到KeyError: 6

    如果你试图在第7个tr标签中搜索div标签,正确的方法应该是:

    containerlv2 = container.find_all('tr')
    related_files = containerlv2[6].find('div')
    

    首先你使用find_all获取container中的所有tr标签并将它们放入列表containerlv2,然后在containerlv2的第7个标签中搜索div

    【讨论】:

      【解决方案2】:
      containerlv2 = container.find('tr')
      

      这会返回一个标签对象,你可以像这样索引一个标签对象

      containerlv2[6]
      

      【讨论】:

        猜你喜欢
        • 2021-04-12
        • 1970-01-01
        • 2021-05-03
        • 1970-01-01
        • 1970-01-01
        • 2017-03-22
        • 2020-12-09
        • 1970-01-01
        相关资源
        最近更新 更多