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()
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...
findAll
, not findall
. <tag>.text
returns a string, and you're testing for an integer.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)