TimeoutError:[Errno 60]操作超时

时间:2020-06-15 16:31:47

标签: python-3.x

以下代码给出了TimeoutError:[Errno 60]操作超时。

通过Chrome或Postman访问该网址时,效果很好。

url:https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY

选项1

import http.client

conn = http.client.HTTPSConnection("www.nseindia.com")
payload = ''
headers = {}
try:
    conn.request("GET", "/api/option-chain-indices?symbol=NIFTY", payload, headers)
    res = conn.getresponse()
    data = res.read()
    print(data.decode("utf-8"))
except http.client.error as e:
    print("exception occurred", e)

选项2

import requests

url = "https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY"
payload = {}
headers = {}

try:
    response = requests.request("GET", url, headers=headers, data=payload)
    response.raise_for_status()
    print(response.text.encode('utf8'))
except requests.HTTPError as exception:
    print("exception occurred", exception)

error : requests.exceptions.ReadTimeout: HTTPSConnectionPool(host='www.nseindia.com', port=443): Read timed out. (read timeout=None)

1 个答案:

答案 0 :(得分:1)

以下代码对我有用。我正在使用Python 3.8。

import requests
import time
import pprint

def fire_get_request(url, headers, timeout=(5,25)):
    start_time = time.time()
    response=requests.get(url, timeout=timeout,headers=headers)
    end_time=time.time() - start_time
    return {'responsetime':end_time,'response':response.text}

url = "https://www.nseindia.com/api/quote-equity?symbol=DHFL&section=trade_info"
# url = "https://httpbin.org/user-agent"
headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36'
            ,"accept": "application/json"
            }
pprint.pprint(fire_get_request(url=url, headers=headers))