Python/XML请求

2024-06-01 01:20:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,尝试申请一个公共交通信息的网站,然后我想在我的树莓皮小显示屏上显示出来。在

import request

xml = """<?xml version="1.0" encoding="UTF-8"?>
<Trias version="1.1" xmlns="http://www.vdv.de/trias" xmlns:siri="http://www.siri.org.uk/siri" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <ServiceRequest>
        <siri:RequestTimestamp>2016-06-27T13:34:00</siri:RequestTimestamp>
        <siri:RequestorRef>EPSa</siri:RequestorRef>
        <RequestPayload>
            <StopEventRequest>
                <Location>
                    <LocationRef>
                        <StopPointRef>8578169</StopPointRef>
                    </LocationRef>
                </Location>
                <Params>
                    <NumberOfResults>5</NumberOfResults>
                    <StopEventType>departure</StopEventType>
                    <IncludePreviousCalls>false</IncludePreviousCalls>
                    <IncludeOnwardCalls>false</IncludeOnwardCalls>
                    <IncludeRealtimeData>true</IncludeRealtimeData>
                </Params>
            </StopEventRequest>
        </RequestPayload>
    </ServiceRequest>
</Trias>"""

headers = {'Authorization': *'#MYCODE'*, 'Content-Type': 'application/xml'}

answer = requests.post('https://api.opentransportdata.swiss/trias', data=xml, headers=headers)

答案是什么:

^{pr2}$

我现在如何继续从中获取一些信息?(对时间表时间和估计时间感兴趣)

我试着用ElementTree,但没用。在

提前谢谢!在

数据提供者的网站:https://opentransportdata.swiss/en/cookbook/departurearrival-display/


Tags: org信息http网站versionwwwxmlheaders
3条回答

I tried to use the ElementTree but it did not really work.

我认为@mzjn在他们提到:注意使用了XML名称空间。

为了防止问题是这样的,下面是一个使用ElementTree解析XML,同时正确处理默认名称空间的示例。在

我用了@andreacatano的答案作为基础。它产生完全相同的输出。在

Python

import xml.etree.ElementTree as ET
from datetime import datetime

test_answer = """<?xml version="1.0" encoding="UTF-8"?>
<Trias xmlns="http://www.vdv.de/trias" version="1.1">
<ServiceDelivery>
    <ResponseTimestamp xmlns="http://www.siri.org.uk/siri">2018-11-19T14:17:42Z</ResponseTimestamp>
    <ProducerRef xmlns="http://www.siri.org.uk/siri">EFAController10.2.9.62-WIN-G0NJHFUK71P</ProducerRef>
    <Status xmlns="http://www.siri.org.uk/siri">true</Status>
    <MoreData>false</MoreData>
    <Language>de</Language>
    <DeliveryPayload>
        <StopEventResponse>
            <StopEventResult>
                <ResultId>ID-8E6262DF-2FB8-4591-97A3-AC3E94E56635</ResultId>
                <StopEvent>
                    <ThisCall>
                        <CallAtStop>
                            <StopPointRef>8578169</StopPointRef>
                            <StopPointName>
                                <Text>Basel, Thomaskirche</Text>
                                <Language>de</Language>
                            </StopPointName>
                            <ServiceDeparture>
                                <TimetabledTime>2018-11-19T14:16:00Z</TimetabledTime>
                                <EstimatedTime>2018-11-19T14:17:00Z</EstimatedTime>
                            </ServiceDeparture>
                            <StopSeqNumber>31</StopSeqNumber>
                        </CallAtStop>
                    </ThisCall>
                    <Service>
                        <OperatingDayRef>2018-11-19</OperatingDayRef>
                        <JourneyRef>odp:05036::H:j18:36143:36143</JourneyRef>
                        <LineRef>odp:05036::H</LineRef>
                        <DirectionRef>outward</DirectionRef>
                        <Mode>
                            <PtMode>bus</PtMode>
                            <BusSubmode>regionalBus</BusSubmode>
                            <Name>
                                <Text>Bus</Text>
                                <Language>de</Language>
                            </Name>
                        </Mode>
                        <PublishedLineName>
                            <Text>36</Text>
                            <Language>de</Language>
                        </PublishedLineName>
                        <OperatorRef>odp:823</OperatorRef>
                        <OriginStopPointRef>8589334</OriginStopPointRef>
                        <OriginText>
                            <Text>Basel, Kleinhüningen</Text>
                            <Language>de</Language>
                        </OriginText>
                        <DestinationStopPointRef>8588780</DestinationStopPointRef>
                        <DestinationText>
                            <Text>Basel, Schifflände</Text>
                            <Language>de</Language>
                        </DestinationText>
                    </Service>
                </StopEvent>
            </StopEventResult>
        </StopEventResponse>
    </DeliveryPayload>
</ServiceDelivery>
</Trias>"""

ns = {"t": "http://www.vdv.de/trias"}

tree = ET.fromstring(test_answer)

# as strings
timetabled_time = tree.find(".//t:TimetabledTime", ns).text
estimated_time = tree.find(".//t:EstimatedTime", ns).text

# as datetime objects
date_format = "%Y-%m-%dT%H:%M:%SZ"
timetabled_time = datetime.strptime(timetabled_time, date_format)
estimated_time = datetime.strptime(estimated_time, date_format)

print("Timetabled time: {} at {}".format(timetabled_time.date(), timetabled_time.time()))
print("Estimated time: {} at {}".format(estimated_time.date(), estimated_time.time()))

输出

^{pr2}$

I tried to use the ElementTree but it did not really work.

正如mzjn所说,你应该向我们提供更多关于你遇到的困难的信息。在

无论如何,如果您想解析xml,我建议使用第三方库来简化您的工作。在我的示例中,我使用了BeautifulSoup

from bs4 import BeautifulSoup
from datetime import datetime

test_answer = """<?xml version="1.0" encoding="UTF-8"?>
<Trias xmlns="http://www.vdv.de/trias" version="1.1">
<ServiceDelivery>
    <ResponseTimestamp xmlns="http://www.siri.org.uk/siri">2018-11-19T14:17:42Z</ResponseTimestamp>
    <ProducerRef xmlns="http://www.siri.org.uk/siri">EFAController10.2.9.62-WIN-G0NJHFUK71P</ProducerRef>
    <Status xmlns="http://www.siri.org.uk/siri">true</Status>
    <MoreData>false</MoreData>
    <Language>de</Language>
    <DeliveryPayload>
        <StopEventResponse>
            <StopEventResult>
                <ResultId>ID-8E6262DF-2FB8-4591-97A3-AC3E94E56635</ResultId>
                <StopEvent>
                    <ThisCall>
                        <CallAtStop>
                            <StopPointRef>8578169</StopPointRef>
                            <StopPointName>
                                <Text>Basel, Thomaskirche</Text>
                                <Language>de</Language>
                            </StopPointName>
                            <ServiceDeparture>
                                <TimetabledTime>2018-11-19T14:16:00Z</TimetabledTime>
                                <EstimatedTime>2018-11-19T14:17:00Z</EstimatedTime>
                            </ServiceDeparture>
                            <StopSeqNumber>31</StopSeqNumber>
                        </CallAtStop>
                    </ThisCall>
                    <Service>
                        <OperatingDayRef>2018-11-19</OperatingDayRef>
                        <JourneyRef>odp:05036::H:j18:36143:36143</JourneyRef>
                        <LineRef>odp:05036::H</LineRef>
                        <DirectionRef>outward</DirectionRef>
                        <Mode>
                            <PtMode>bus</PtMode>
                            <BusSubmode>regionalBus</BusSubmode>
                            <Name>
                                <Text>Bus</Text>
                                <Language>de</Language>
                            </Name>
                        </Mode>
                        <PublishedLineName>
                            <Text>36</Text>
                            <Language>de</Language>
                        </PublishedLineName>
                        <OperatorRef>odp:823</OperatorRef>
                        <OriginStopPointRef>8589334</OriginStopPointRef>
                        <OriginText>
                            <Text>Basel, Kleinhüningen</Text>
                            <Language>de</Language>
                        </OriginText>
                        <DestinationStopPointRef>8588780</DestinationStopPointRef>
                        <DestinationText>
                            <Text>Basel, Schifflände</Text>
                            <Language>de</Language>
                        </DestinationText>
                    </Service>
                </StopEvent>
            </StopEventResult>
        </StopEventResponse>
    </DeliveryPayload>
</ServiceDelivery>
</Trias>"""

soup = BeautifulSoup(test_answer, "html.parser")
service_departure = soup.find("servicedeparture")

# as Tag objects
timetabled_time = service_departure.timetabledtime
estimated_time = service_departure.estimatedtime

# as strings
timetabled_time = timetabled_time.text
estimated_time = estimated_time.text

# as datetime objects
date_format = "%Y-%m-%dT%H:%M:%SZ"
timetabled_time = datetime.strptime(timetabled_time, date_format)
estimated_time = datetime.strptime(estimated_time, date_format)

print("Timetabled time: {} at {}".format(timetabled_time.date(), timetabled_time.time()))
print("Estimated time: {} at {}".format(estimated_time.date(), estimated_time.time()))

打印:

^{pr2}$

如果您想坚持使用标准Python,可以使用:html.parser在

https://docs.python.org/3/library/html.parser.html

python还有很多第三方库可以让你更轻松地解析html)

相关问题 更多 >