Skip to main content
 首页 » 编程设计

Python BeautifulSoup : 'list_iterator' object is not subscriptable

2024年12月31日11itcoder

我正在尝试从以下 html 结构中提取文本:

<div class="account-age"> 
    <label></label> 
    <div> 
        <div> 
             <span>Text to extract</span> 
        </div> 
    </div> 
</div> 

我有以下 Beautiful Soup 代码可以做到这一点:

from bs4 import BeautifulSoup as bs 
 
soup = bs(html, "lxml") 
div = soup.find("div", {"class": "account-age"}) 
span = div.children[1].children[0].children[0] 
text = span.get_text() 

不幸的是,Beautiful Soup 抛出错误:“list_iterator”对象不可订阅。我该如何解决这个问题以提取我需要的文本?

请您参考如下方法:

您可以通过直接从根 div 链接标签来做到这一点:

div.div.div.span.get_text() 
# u'Text to extract'