iT邦幫忙

0

python 轉json有誤

2023-01-31 14:37:47686 瀏覽
  • 分享至 

  • xImage

with open('Dcard-articles.json', 'w', encoding='utf-8') as f:
json.dump(results, f, indent=4,
sort_keys=True, ensure_ascii=False)
程式碼如上,但會出現錯誤:
Object of type WebElement is not JSON serializable
是哪裡有誤?該如何解決?請幫幫我這初學,網路上找也有點看不懂

Rex Chien iT邦新手 4 級 ‧ 2023-01-31 16:28:42 檢舉
看起來你的 `results` 是 selenium 抓回來還沒處理過的
dumps
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

2
akitect
iT邦新手 5 級 ‧ 2023-01-31 18:44:30
最佳解答

你所參考的 文章 部份内容已經過時:

  1. 關於 selenium 的部份,find_element_by_* 已經在新版被棄用,例如當中的
eles = driver.find_elements_by_class_name("tgn9uw-0")

應該要改為

from selenium.webdriver.common.by import By

eles = driver.find_element(By.CLASS_NAME, "tgn9uw-0")
  1. 網站有所變動,class name 已經由 tgn9uw-0 變為 c122gkvw,原因可能是 Dcard 使用了 CSS-loader,令 class name 為人類無法閱讀的樣式,以 class name 作爬取條件並不穩定。

有興趣了解可見:Why Google use random ClassName


個人認為可以使用

post = driver.find_element(By.TAG_NAME, "article")

去代替參考文章中 eles 的爬取,後續研究 selenium打開使用方式去解析所需要的資料、適當在 Dcard 網站開啟開發者工具 (DevTools) 研究可用的 locator。


另外,不確定你 selenium 的版本和實際輸出,selenium 部份 method 也已經被棄用,有機會是 results 未經處理,仍然是 WebElement 導致。

0
hokou
iT邦好手 1 級 ‧ 2023-01-31 14:51:56

你的 results 結果是什麼呢?
應該不是 JSON 的格式吧

【Day 3】常見的資料格式 (2/3) - JSON
Day11 - Python 如何處理 JSON
JSON 檔案操作

iT邦新手 5 級 ‧ 2023-01-31 16:29:27 檢舉

我是參考這篇的https://ithelp.ithome.com.tw/articles/10277622
基本的code都一樣但我最後有誤

hokou iT邦好手 1 級 ‧ 2023-01-31 16:48:25 檢舉


我看那篇最後有 print(results)
你的 results 格式跟他的照片結果是一致的嗎

results = []
result = {
            'title': title,
            'href': href,
            'subtitle': subtitle
        }
results.append(result)

因為爬蟲很容易對方網站改版而有變動
搞不好他的 classname 已經變了,不是 'tgn9uw-0'
driver.find_elements_by_class_name('tgn9uw-0')

所以很可能只是一個空的 results
因此不滿足 JSON 格式

iT邦新手 5 級 ‧ 2023-01-31 18:09:41 檢舉

他的那些部份我都有改掉,格式是一樣的,results也是有東西的

我要發表回答

立即登入回答