python - 美汤生第一个 child

标签 python beautifulsoup

我怎样才能得到第一个 child ?

 <div class="cities"> 
       <div id="3232"> London </div>
       <div id="131"> York </div>
  </div>

我怎样才能到达伦敦?

for div in nsoup.find_all(class_='cities'):
    print (div.children.contents)

AttributeError: 'listiterator' 对象没有属性 'contents'

最佳答案

div.children 返回一个迭代器。

for div in nsoup.find_all(class_='cities'):
    for childdiv in div.find_all('div'):
        print (childdiv.string) #london, york

引发了 AttributeError,因为像 '\n' 这样的非标签在 .children 中。只需使用适当的子选择器来查找特定的 div。

(更多编辑)无法重现您的异常 - 这是我所做的:

In [137]: print foo.prettify()
<div class="cities">
 <div id="3232">
  London
 </div>
 <div id="131">
  York
 </div>
</div>

In [138]: for div in foo.find_all(class_ = 'cities'):
   .....:     for childdiv in div.find_all('div'):
   .....:         print childdiv.string
   .....: 
 London 
 York 

In [139]: for div in foo.find_all(class_ = 'cities'):
   .....:     for childdiv in div.find_all('div'):
   .....:         print childdiv.string, childdiv['id']
   .....: 
 London  3232
 York  131

关于python - 美汤生第一个 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15490718/

相关文章:

python - 使用 beautifulsoup 美化 html 文档的一部分

python - Pygame碰撞检测问题

python - 为什么使用nc连接时python代码执行顺序错误?

python - Pandas - 带有另一个数据框python索引列表的列

python - Pandas 数据框更新 key

python - 无法在 BeautifulSoup 中链接 find 和 find_all

python - beautifulsoup - 忽略 unicode 错误并仅打印文本

python - 解析源代码(Python)方法: Beautiful Soup, lxml、html5lib区别?

python - 在 href 标签中查找部分匹配项

python - 使用BeautifulSoup python 时出错