Search code examples
pythonxmlbeautifulsoupinteraction

Interacting with xml files using BeautifulSoup and If statements


I am using BeautifulSoup4 to extract data from a live xml data, and I am trying to interact with one of the tags within that xml file, preferably with if/else statements.

Here is a portion of the xml:

TAG: isApp>1 >isApp

Tag isApp updates itself from 1 or 0, meaning that the train is approaching(1).

I have my code to extract the data and update the data each time I run it, but now I want to interact with the tags using if/else statements and I am having an issue with it.

For example, I need something to run if a train is at 1 and does nothing when at 0.

if 'isApp' == 1:
    print('Test')

Here is my code:

from bs4 import BeautifulSoup

req = urllib.request.urlopen("http://lapi.transitchicago.com/api/1.0/ttpositions.aspx?key=5c78297a2f28427e9b87435118367766&rt=red,blue,G,pink,Brn,Org,P,Y")

xml = BeautifulSoup(req, 'xml')

def xmlparse():

   for item in xml.findall('isApp'):

if True:  
    print(item.text)

else:     
    print("False")
    xmlparse()

Solution

  • Your code example seems to have some formatting issues, and what you're asking for in the text explanation seems to be different than what you are trying to do in your code sample, but...

    1. You need to call the correct method in BeautifulSoup: findAll, not findall.
    2. <tag>.text returns a string, and you're testing for an integer.
    3. The formatting alone of your sample code would prevent it from working.

    Here's some code that does what it appears you are trying to do:

    import urllib
    from bs4 import BeautifulSoup
    
    req = urllib.request.urlopen("http://lapi.transitchicago.com/api/1.0/ttpositions.aspx?key=5c78297a2f28427e9b87435118367766&rt=red,blue,G,pink,Brn,Org,P,Y")
    
    content = BeautifulSoup(req, 'xml')
    
    def xmlparse(xml):
        for item in xml.findAll('isApp'):
            if item.text == '1':
                print('Test')  # or do whatever you want when True ("1")
            else:
                print('False') # or do whatever you want when False ("0")
    
    xmlparse(content)