How to get an attribute value using BeautifulSoup and Python?

前端 未结 3 1641
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-15 11:52

I\'m failing miserably to get an attribute value using BeautifulSoup and Python. Here is how the XML is structured:

...


    

        
3条回答
  •  春和景丽
    2020-12-15 12:19

    The problem is that find_all('tag') returns the whole html block entitled tag:

    >>> results.find_all('tag')                                                                      
    [                                                                                     
    TR=111111 Sandbox=3000613                                   
    TR=121212 Sandbox=3000618                                   
    TR=999999 Sandbox=3000617                                   
    ]
    

    Your intention is to collect each of the stat blocks, so you should be using results.find_all('stat'):

    >>> stat_blocks = results.find_all('stat')                                                                      
    [TR=111111 Sandbox=3000613, TR=121212 Sandbox=3000618, TR=999999 Sandbox=3000617]
    

    From there, it is trivial to fix the code to condense 'pass' into a list:

    >>> passes = [s['pass'] if s is not None else None for s in stat_blocks]                   
    >>> passes                                                                                   
    ['1', '1', '1']  
    

    Or print:

    >>> for s in stat_blocks:                                                                  
    ...     print(s['pass'])                                                                   
    ...                                                                                        
    1                                                                                          
    1                                                                                          
    1     
    

    In python, it's really important to test results because the typing is way too dynamic to trust your memory. I often include a static test function in classes and modules to ensure that the return types and values are what I expect them to be.

提交回复
热议问题