logo
Loading...

資料整理問題 - Cupoy

我在使用xmltodict時,要從location往下到weatherElement時,會出現此格式...

pycrawler,pycrawler-d03

資料整理問題

2019/11/23 下午 03:25
Python網路爬蟲討論版
zero0827z
觀看數:20
回答數:3
收藏數:0
pycrawler
pycrawler-d03

我在使用xmltodict時,要從location往下到weatherElement時,會出現此格式不可以為文字格式,所以無法再往下細分出時間與溫度,

想詢問是否我哪裡有做錯?


code:

data=d['cwbopendata']['dataset']['locations']['location']['weatherElement']


log:

TypeError                                 Traceback (most recent call last) <ipython-input-189-aad7c070e8aa> in <module>      1# 2. 請取出每一個地區所記錄的第一個時間點跟溫度----> 2data=d['cwbopendata']['dataset']['locations']['location']['weatherElement']TypeError: list indices must be integers or slices, not str

回答列表

  • 2019/11/23 下午 05:42
    Jeffrey
    贊同數:0
    不贊同數:1
    留言數:0

    提供一個範例:

    from bs4 import BeautifulSoup

    soup = BeautifulSoup(open('index.html'))

    img_tag = div.select_one("img")

    src = img_tag['src']

    print(src)

  • 2019/11/23 下午 08:12
    K.F
    贊同數:3
    不贊同數:0
    留言數:1

    你好阿

    簡單說問題是因為

    location有很多個

    你必須指定要用哪個location

    所以它提示了你

    list索引要帶入數字而不是指定字串

    你用

    data=d['cwbopendata']['dataset']['locations']['location'][0]['weatherElement']

    應該就知道意思了

  • 2019/11/25 下午 10:14
    張維元 (WeiYuan)
    贊同數:2
    不贊同數:0
    留言數:0

    嗨,因為這邊:


    ```

    d['cwbopendata']['dataset']['locations']['location']

    ```


    回傳的是 List 型態,所以只能用位置的方式做選擇。這個練習想讓大家熟悉各種資料的整理過程:)