我正在使用 BeautifulSoup4
从实时 xml 数据中提取数据,并且我正在尝试与该 xml 文件中的标签之一进行交互,最好使用 if/else
声明。
这是 xml 的一部分:
标签:isApp>1 >isApp
标签 isApp
从 1 或 0 更新自身,表示火车正在接近 (1)。
我有代码来提取数据并在每次运行时更新数据,但现在我想使用 if/else
语句与标签进行交互,但我遇到了问题。
例如,如果火车在 1 处运行,而在 0 处不执行任何操作,我需要运行一些东西。
if 'isApp' == 1:
print('Test')
这是我的代码:
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()
最佳答案
您的代码示例似乎存在一些格式问题,并且您在文本解释中要求的内容似乎与您在代码示例中尝试执行的操作不同,但是...
- 您需要在 BeautifulSoup 中调用正确的方法:
findAll
,不是findall
。 -
<tag>.text
返回一个字符串,并且您正在测试一个整数。 - 仅对示例代码进行格式化就会导致其无法运行。
这里有一些代码可以完成您想要做的事情:
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)
关于python - 使用 BeautifulSoup 和 If 语句与 xml 文件交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48268571/