[英]Unable to save json data using python and selenium
我正在嘗試從https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY保存 json 數據。 data.json 文件是空的。 這是代碼
import time, json
from selenium import webdriver
driver = webdriver.Firefox()
url = "https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY"
driver.get(url)
time.sleep(5)
button = driver.find_element_by_id("rawdata-tab")
button.click()
data = driver.find_element_by_class_name("data").text
d = json.loads(data)
with open('data.json', 'w') as f:
json.dumps(d, default=lambda o: '<not serializable>')
time.sleep(10)
driver.close()
找不到我哪里出錯了,有沒有更好的方法來實現這一目標?
正如我在評論中提到的那樣,硒用於網頁抓取或更普遍地模仿網頁上的人類行為。 但是您的網址不會生成網頁。 現在,據我所知,試試這個:
import json, requests
url = "https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY"
response = requests.get(url)
d = response.json()
with open('data.json', 'w') as f:
json.dumps(d, default=lambda o: '<not serializable>')
由於您的 url 已經生成 json,因此我只是使用requests
來獲取它,它生成一個有效的 json,然后您可以根據需要將其寫入文件。
PS:試着理解你在代碼中寫的任何東西,因為這將幫助你調試,否則你總是會卡在某個地方。
只需在您的請求標頭中添加一個用戶代理
import requests
headers={'User-Agent':'Mozilla/5.0 (Android 4.2.1; Mobile; rv:32.0) Gecko/32.0 Firefox/32.0'}
url = "https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY"
data = requests.get(url, headers=headers)
with open('data.json', 'w') as f:
f.write(data.text)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.