Beautifulsoup 异常列表超出范围

Ryf*_*lex 2 python exception list beautifulsoup python-2.7

我正在使用 beautifulsoup 来执行以下操作:
section = soup.findAll('tbody')[0]

如何使用第一个列表项设置这样的变量...而不抛出异常:IndexError: list index out of range如果 BS4 找不到 tbody?

有任何想法吗?

B.M*_*.W. 5

每个解析 HTML 的人都会遇到这种类型的问题。您要查找的元素位于嵌套结构中... table -> tbody -> tr -> td ... etc...

但是,您需要记住以下几点:

(1) 指定查找元素的路径越详细。如果您没有正确处理异常,您的代码就越容易中断,实际上,您找到路径的逻辑可能根本不通用。

(2) 尝试通过唯一的 id 或类来定位元素,而不是依靠一些通用标签的顺序..

(3) 如果您尝试收集的文本遵循某种模式。您可以使用文本本身轻松找到它,这对程序员来说更直接......文本是人们实际看到的。

import re
...
print soup.find_all(text=re.compile("pattern"))
# then you can find the element by calling parent of the found texts.
Run Code Online (Sandbox Code Playgroud)

简而言之,在我看来,永远不要搜索“tbody”标签……因为代码总是这样的:

<table..>
    <tbody>
        <tr>
        ...
    </tbody>
<table>
Run Code Online (Sandbox Code Playgroud)

如果你已经找到了桌子,你可以做

table = soup.find('table'...)
# unless you are trying to not recursively find tr, then you have to find tobody first and find_all(recursive=FALSE)
table.find_all('tr')
Run Code Online (Sandbox Code Playgroud)