使用 BeautifulSoup 和 If 语句与 xml 文件交互

Interacting with xml files using BeautifulSoup and If statements

我正在使用 BeautifulSoup4 从实时 xml 数据中提取数据,并且我正在尝试与该 xml 文件中的其中一个标签进行交互,最好是 if/else 语句。

这是 xml 的一部分:

TAG: 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()

您的代码示例似乎存在一些格式问题,您在文本说明中要求的内容似乎与您在代码示例中尝试执行的操作不同,但是...

  1. 您需要在 BeautifulSoup 中调用 正确的方法findAll,而不是 findall
  2. <tag>.text returns 一个字符串,而您正在测试一个整数。
  3. 仅您的示例代码的格式会阻止它工作。

这里有一些代码可以执行您正在尝试执行的操作:

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)