6

When I use:

import requests
r = requests.get("https://example.com")  

I get the following exception:

requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)

However, If i use following code:

url = "https://www.example.com"
request = urllib.request.urlopen(url)

It gives me the correct response[200] code. Why is it so? What is the difference between these two methods and which one should be preferred?

Carl
  • 853
  • 9
  • 23
Anmol Bhatia
  • 326
  • 2
  • 5
  • 12

2 Answers2

9

Use the former one: I will add the source of why it's better. Anyways you need to set verify as False to prevent requests from verifying SSL certificates for HTTPS requests:

import requests
r = requests.get("https://example.com", verify=False)

Edit:

Difference between requests.get() and urllib.request.urlopen() python

What are the differences between the urllib, urllib2, and requests module?

Carl
  • 853
  • 9
  • 23
Devi Prasad Khatua
  • 1,185
  • 3
  • 11
  • 23
  • So correct me if i am wrong,request.get() [with default verify=true] will try to verify the certificate and urllib.request.urlopen() does not do that. – Anmol Bhatia Jun 30 '16 at 05:52
  • it's done explicity by using https connection https://docs.python.org/2/library/httplib.html#httplib.HTTPSConnection – Devi Prasad Khatua Jun 30 '16 at 05:58
  • Thanks, i got it now. Its always better to use request.get/post so that it will perform ssl verification for you. Thanks for the clarification! – Anmol Bhatia Jun 30 '16 at 06:01
1

This is happening because example.com does not have a valid certificate. So requests warns you that the https connection won't be trusted. If you trust the server then you should do what wolframalpha suggested.

Kroustou
  • 659
  • 5
  • 14