【问题标题】:iterating through array using beautifulsoup使用 beautifulsoup 遍历数组
【发布时间】:2023-01-28 22:16:35
【问题描述】:

我有以下问题:

from bs4 import BeautifulSoup as bs

path_xml = r"..."

content = []

with open(path_xml, "r") as file:
    content = file.readlines()

content = "".join(content)
bs_content = bs(content, "html.parser")

bilder = bs_content.find_all("bilder")

def get_str_bild(match):
    test = match.findChildren("b")

    for x in range(len(test)): # here is the problem (not giving me all elements in test)
 
        return test[x].get("d")

for b in bilder:
    if b.b: 
        print(get_str_bild(b))

输出:

L3357U00_002120.jpg
L3357U00_002140.jpg
L3357U00_002160.jpg

基本上,在 xml 文件中有 3 个位置,我有节点`bilder.每个块看起来像这样:

      <Bilder>
        <B Nr="1" D="L3357U00_002120.jpg"/>
        <B Nr="2" D="L3357U00_002120.jpg"/>
        <B Nr="3" D="L3357U00_002120.jpg"/>
        <B Nr="4" D="L3357U00_002120.jpg"/>
        <B Nr="9" D="L3357U00_002120.jpg"/>
        <B Nr="1" D="L3357U00_002130.jpg"/>
        <B Nr="2" D="L3357U00_002130.jpg"/>
        <B Nr="3" D="L3357U00_002130.jpg"/>
        <B Nr="4" D="L3357U00_002130.jpg"/>
        <B Nr="9" D="L3357U00_002130.jpg"/>
      </Bilder>

目前它只返回每个块的第一张图片,我想返回所有这些图片。

我在这里做错了什么?

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    您需要修复get_str_bild(match) 函数。它当前返回第一个 d 属性。

    用这个替换你的功能:

    def get_str_bild(match):
        test = match.find_all("b")
        
        elements = []
        for x in range(len(test)):
            elements.append(test[x].get("d"))
    
        return elements
    

    【讨论】:

      【解决方案2】:

      您错过了 bs of your biders 的循环。您可以删除函数并简化代码,如下所示:

      bs_content = bs(content, "html.parser")
      for i, builder in enumerate(bs_content.find_all("bilder")):
          print(f'builder {i}')
          for b in bilder.find_all('b'):
              print(b['d'])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-25
        • 1970-01-01
        • 1970-01-01
        • 2012-05-05
        • 1970-01-01
        • 2014-07-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多