xml페이지를 python3, beautifulsoup를 이용해서 파싱하는데 인덱스 에러가 납니다.

조회수 5079회

BASE_URL = "http://openapi.gbis.go.kr/ws/rest/buslocationservice?serviceKey=%2BFdkupBYoTx3q0Sd%2B6GFPa6NZ0Quorkb0guP7oMfTj8I75dQKX8vhMXO4QoY6KLZwx%2Bja8eT7irD11Gxv31t1g%3D%3D&routeId=200000085"

responses = requests.get(BASE_URL)
print (responses.status_code)
dom = BeautifulSoup(responses.content, "html.parser")
elements = dom.select("span.text")
element = elements[0]

이 코드를 실행하면 아래와 같은 인덱스에러가 발생합니다.

element = elements[0]

IndexError: list index out of range

저 페이지에서 routeId, stationId, stationSeq 등을 뽑아오고 싶은데 코드를 아무리 바꿔보아도 인덱스에러가 나는 건 select안에 태그이름을 잘못 설정해서 일까요?

  • (•́ ✖ •̀)
    알 수 없는 사용자

1 답변

  • 해당 url에 접속해보면 html이 아니라 xml데이터를 리턴합니다. 따라서 html parse가 아니라 xml parser를 사용하여 데이터를 가져와야 합니다. beautifulsoup 문서를 보면 xml parser로 lxml parser를 사용합니다. 우선 lxml parser를 설치하시고, 아래 코드를 실행해보세요.

    from bs4 import BeautifulSoup
    import requests
    
    BASE_URL = "http://openapi.gbis.go.kr/ws/rest/buslocationservice?serviceKey=%2BFdkupBYoTx3q0Sd%2B6GFPa6NZ0Quorkb0guP7oMfTj8I75dQKX8vhMXO4QoY6KLZwx%2Bja8eT7irD11Gxv31t1g%3D%3D&routeId=200000085"
    
    responses = requests.get(BASE_URL)
    soup = BeautifulSoup(responses.content, 'lxml-xml')
    
    for busLocation in soup.findAll('busLocationList'):
      stationId = busLocation.find('stationId')
      plateNo = busLocation.find('plateNo')
      print("StationId: " + stationId.string + " PlateNo: " + plateNo.string)
    
    • (•́ ✖ •̀)
      알 수 없는 사용자

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)