【问题标题】:Convert Scraped Data to Dictionary将抓取的数据转换为字典
【发布时间】:2020-02-21 19:23:05
【问题描述】:

我有一个 XML 文件,在我运行 Beautiful soup findAll("named-query") 并将其打印出来后,我得到如下结果:

<named-query name="sdfsdfsdf">
        <query>
            ---Query here...--
        </query>
</named-query>

<named-query name="xkjlias">
        <query>
          ---Query here...--
        </query>
</named-query>
   .
   .
   .

有没有办法可以将其转换为字典、json 或 csv 之类的:

name="sdfsdfsdf" 查询 = ....

name="xkjlias" 查询 = ....

提前致谢。

【问题讨论】:

    标签: python beautifulsoup scrapy


    【解决方案1】:

    代码:

    import json
    
    from bs4 import BeautifulSoup
    
    
    text = """
    <named-query name="sdfsdfsdf">
        <query>
            ---Query here...--
        </query>
    </named-query>
    
    <named-query name="xkjlias">
        <query>
            ---Query here2...--
        </query>
    </named-query>"""
    
    
    soup = BeautifulSoup(text, 'html.parser')
    queries = {nq.attrs['name']: nq.text.strip() for nq in soup.find_all('named-query')}
    queries_json = json.dumps(queries)
    
    print(queries)  # dict
    print(queries_json)  # json
    
    

    输出:

    {'sdfsdfsdf': '---Query here...--', 'xkjlias': '---Query here2...--'}
    {"sdfsdfsdf": "---Query here...--", "xkjlias": "---Query here2...--"}
    

    【讨论】:

      【解决方案2】:

      试试这个:

      # initialize a dictionary
      data = {}
      
      # for each tag 'named-query 
      for named_query in soup.findAll('named-query'):
              # get the value of name attribute and store it in a dict
              data['name'] = named_query.attrs['name']
              # traverse its children
              for child in named_query.children:
                      # check for '\n' and empty strings
                      if len(child.string.strip()) > 0:
                              data['query'] = child.string.strip()
      print (data)
      
      
      >>> {'name': 'sdfsdfsdf', 'query': '---Query here...--'}
      

      【讨论】:

        猜你喜欢
        • 2021-06-21
        • 2021-06-19
        • 2022-07-05
        • 1970-01-01
        • 2021-04-08
        • 2019-08-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多