【问题标题】:How to extract value of attribute in a nested tag structure using beautifulsoup?如何使用 beautifulsoup 提取嵌套标签结构中的属性值?
【发布时间】:2012-07-17 00:01:48
【问题描述】:

我有一个看起来与此类似的 html 文件:

<html>
...
<li class="not a user"> </li>
<li class="user">
 <a href="abs" ...> </a>
</li>
<li class="user">
 <a href="bss" ...> </a>
</li>
...
</html>

鉴于上述输入,我想用 class="user" 解析 li 标签并获取 href 的值作为输出。这可能在python中使用beautifulsoup吗???

我的解决方案是:

data="the above html code snippet"
soup=BeautifulSoup(data)
listset=soup("li","user")
for list in listset:
   attrib_value=[a['href'] for a in list.findAll('a',{'href':True})]

显然我在某处有一个错误,它只列出了最后一个锚标记的 href 的属性值。

【问题讨论】:

  • 为什么要在每个循环中一遍又一遍地设置 attrib_value?你在每次迭代中用它做什么?
  • 问题是当我想要一个属性值列表时,我只是在每次迭代中不断重新分配! :P

标签: python html parsing beautifulsoup


【解决方案1】:

您的代码很好。 listset 中有三个元素 - 并且 attrib_value 在循环的每次迭代中都会被覆盖,因此在程序结束时,它仅包含来自 listset 的最后一个元素的 href 值,即 bss .

尝试这样做以保留所有值:

attrib_value += [a['href'] for a in list.findAll('a',{'href':True})]

并在循环之前将attrib_value初始化为空列表(attrib_value = [])。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    • 2018-04-23
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    相关资源
    最近更新 更多