繁体   English   中英

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

[英]Soup.select, get only first result back

有什么办法可以从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')给出相同的结果

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM