Skip to main content
 首页 » 编程设计

python之Soup.select,只返回第一个结果

2024年10月24日12落叶无声

有什么方法可以从 for i soup.select(table) 中获取第一个结果吗?我只想要第一个表,它之后的每个表都应该被忽略。代码后跟一个 if 语句:if i.find('th', text = 'Foo'):

TLDR;

寻找这样的东西:if i[0].find('th', text = 'Foo'):

请您参考如下方法:

一种方法是在第一次迭代后立即break:

for i in soup.select('table'): 
    if i.find('th', text = 'Foo'): 
        ... 
    break 

另一种是链接方法,如果找不到元素则捕获异常:

try: 
    el = soup.select('table')[0].find('th', text='Foo') 
except AttributeError, TypeError: 
    print('element not found') 

注意:soup.select('table')[0] 和 soup.find('table') 给出相同的结果