Winerror 10060 python как исправить

I have follow this tutorial but I still fail to get output. Below is my code in view.py

def index(request):

 #html="a"
 #url= requests.get("https://www.python.org/")
 #page = urllib.request.urlopen(url)
 #soup = BeautifulSoup(page.read())
 #soup=url.content
 #urllib3.disable_warnings()
 #requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
 #url=url.content
 #default_headers = make_headers(basic_auth='myusername:mypassword')
 #http = ProxyManager("https://myproxy.com:8080/", headers=default_headers)

 r = urllib.request.urlopen('http://www.aflcio.org/Legislation-and-Politics/Legislative-Alerts').read()
 soup = BeautifulSoup(r)
 url= type(soup)

 context={"result":url,}
 return render (request, 'index.html',context)

Output:

urlopen error [WinError 10060] A connection attempt failed because the
connected party did not properly respond after a period of time, or
established connection failed because connected host has failed to respond

Neuron's user avatar

Neuron

5,0235 gold badges38 silver badges58 bronze badges

asked Jun 23, 2017 at 0:30

Shi Jie Tio's user avatar

7

If you are sitting behind a firewall or similar you might have to specify a proxy for the request to get through.

See below example using the requests library.

import requests

proxies = {
  'http': 'http://10.10.1.10:3128',
  'https': 'http://10.10.1.10:1080',
}

r = requests.get('http://example.org', proxies=proxies)

answered Apr 12, 2019 at 10:02

Håkan Svensson's user avatar

0

py.user.next спасибо, ошибки связанной с этой переменной более не возникает.
подскажите, а как в эту конструкцию добавить передачу хедера, например:

head = {‘User-Agent’: ‘Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11’,
‘Accept’: ‘text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8’,
‘Accept-Charset’: ‘ISO-8859-1,utf-8;q=0.7,*;q=0.3’,
‘Accept-Encoding’: ‘none’,
‘Accept-Language’: ‘en-US,en;q=0.8’,
‘Connection’: ‘keep-alive’}

иначе сервер отдает 403ю ошибку на запрос, видно ему не нравится питоновский заголовок.
пробовал всунуть в запрос
urllib.request.urlopen(url) в виде urllib.request.urlopen(url, head) — не работает, хотя по описанию там можно передавать данные.

C:UserspankaAppDataLocalProgramsPythonPython35-32python.exe C:/Users/panka/PycharmProjects/bucky/webCrawling.py
Traceback (most recent call last):
File «C:UserspankaAppDataLocalProgramsPythonPython35-32libsite-packagesurllib3connection.py», line 141, in _new_conn
(self.host, self.port), self.timeout, **extra_kw)
File «C:UserspankaAppDataLocalProgramsPythonPython35-32libsite-packagesurllib3utilconnection.py», line 83, in create_connection
raise err
File «C:UserspankaAppDataLocalProgramsPythonPython35-32libsite-packagesurllib3utilconnection.py», line 73, in create_connection
sock.connect(sa)
TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File «C:UserspankaAppDataLocalProgramsPythonPython35-32libsite-packagesurllib3connectionpool.py», line 601, in urlopen
chunked=chunked)
File «C:UserspankaAppDataLocalProgramsPythonPython35-32libsite-packagesurllib3connectionpool.py», line 346, in _make_request
self._validate_conn(conn)
File «C:UserspankaAppDataLocalProgramsPythonPython35-32libsite-packagesurllib3connectionpool.py», line 850, in _validate_conn
conn.connect()
File «C:UserspankaAppDataLocalProgramsPythonPython35-32libsite-packagesurllib3connection.py», line 284, in connect
conn = self._new_conn()
File «C:UserspankaAppDataLocalProgramsPythonPython35-32libsite-packagesurllib3connection.py», line 150, in _new_conn
self, «Failed to establish a new connection: %s» % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.VerifiedHTTPSConnection object at 0x03C85FB0>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File «C:UserspankaAppDataLocalProgramsPythonPython35-32libsite-packagesrequestsadapters.py», line 440, in send
timeout=timeout
File «C:UserspankaAppDataLocalProgramsPythonPython35-32libsite-packagesurllib3connectionpool.py», line 639, in urlopen
_stacktrace=sys.exc_info()[2])
File «C:UserspankaAppDataLocalProgramsPythonPython35-32libsite-packagesurllib3utilretry.py», line 388, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host=’buckysroom.org’, port=443): Max retries exceeded with url: /trade/search.php?page=1 (Caused by NewConnectionError(‘<urllib3.connection.VerifiedHTTPSConnection object at 0x03C85FB0>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond’,))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File «C:/Users/panka/PycharmProjects/bucky/webCrawling.py», line 39, in
trade_spider(1)
File «C:/Users/panka/PycharmProjects/bucky/webCrawling.py», line 9, in trade_spider
source_code = requests.get(url)
File «C:UserspankaAppDataLocalProgramsPythonPython35-32libsite-packagesrequestsapi.py», line 72, in get
return request(‘get’, url, params=params, **kwargs)
File «C:UserspankaAppDataLocalProgramsPythonPython35-32libsite-packagesrequestsapi.py», line 58, in request
return session.request(method=method, url=url, **kwargs)
File «C:UserspankaAppDataLocalProgramsPythonPython35-32libsite-packagesrequestssessions.py», line 508, in request
resp = self.send(prep, **send_kwargs)
File «C:UserspankaAppDataLocalProgramsPythonPython35-32libsite-packagesrequestssessions.py», line 618, in send
r = adapter.send(request, **kwargs)
File «C:UserspankaAppDataLocalProgramsPythonPython35-32libsite-packagesrequestsadapters.py», line 508, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host=’buckysroom.org’, port=443): Max retries exceeded with url: /trade/search.php?page=1 (Caused by NewConnectionError(‘<urllib3.connection.VerifiedHTTPSConnection object at 0x03C85FB0>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond’,))

Process finished with exit code 1

Здравствуйте, имею небольшой скрипт на Py, по отправке сообщения через SMPT сервер Яндекса:

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

import smtplib

def send_email(recipient, subject, msg):
    sender = 'mail@yandex.ru'
    password = 'mailpass'    
    
    server = smtplib.SMTP('smpt.yandex.ru', 587)
    server.starttls()

    try:
        server.login(sender, password)
        msg = MIMEText(msg)
        msg['Subject'] = subject
        server.sendmail(sender, recipient, msg.as_string())
        return 'Message send'
    except Exception as exception:
        return f'Check ur credentailsn{exception}'
    
def main():
    recipient = input('Enter recipient')
    subject = input('Enter subject')
    msg = input('Enter msg')

    print(send_email(recipient, subject, msg))

if __name__ == '__main__':
    main()

При попытке отправки письма содержания «123» возникает следующая ошибка:

Traceback (most recent call last):
  File "c:UsersUserDesktopprojmain.py", line 30, in <module>
    main()
  File "c:UsersUserDesktopprojmain.py", line 27, in main
    print(send_email(recipient, subject, msg))
  File "c:UsersUserDesktopprojmain.py", line 10, in send_email   
    server = smtplib.SMTP('smpt.yandex.ru', 587)
  File "C:UsersUserAppDataLocalProgramsPythonPython310libsmtplib.py", line 255, in __init__
    (code, msg) = self.connect(host, port)
  File "C:UsersUserAppDataLocalProgramsPythonPython310libsmtplib.py", line 341, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "C:UsersUserAppDataLocalProgramsPythonPython310libsmtplib.py", line 312, in _get_socket
    return socket.create_connection((host, port), timeout,
  File "C:UsersUserAppDataLocalProgramsPythonPython310libsocket.py", line 845, in create_connection
    raise err
  File "C:UsersUserAppDataLocalProgramsPythonPython310libsocket.py", line 833, in create_connection
    sock.connect(sa)
TimeoutError: [WinError 10060] Попытка установить соединение была безуспешной, т.к. от другого компьютера за требуемое время не получен нужный отклик, или было разорвано уже установленное соединение из-за неверного отклика уже подключенного компьютера

В какую сторону копать?
Пробовал запускать этот код с двух разных машин.

I am trying to connect to server, Here is my piece of code

import socket
HOST = '192.168.10.11'
PORT = 5060
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))

I get the following TimeoutError:

   Traceback (most recent call last):
   File "D:Trails/calltest.py", line 7, in <module>
    s.connect((HOST, PORT))
   TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

I tried if the port is working or not

~# nmap -p 5060 -sU -P0 192.168.10.11

I got the reply

Starting Nmap 6.40 ( http://nmap.org ) at 2018-05-11 19:44 IST
Nmap scan report for 192.168.10.11
Host is up.
PORT     STATE         SERVICE
5060/udp open|filtered sip

Why am I not able to connect? Any help appreciated!

Понравилась статья? Поделить с друзьями:
  • Как найти сюжет на дзене
  • Как в симуляторе мыши найти человека
  • Как найти любимого с помощью молитвы
  • Как составить свою новогоднюю историю
  • Как найти наставника бесплатно