How to open remote content with python?

Asked

Viewed 392 times

4

In PHP, when I want to get a remote content (some url, for example), I use my own functions to open files and it works perfectly.

Example:

file_get_contents('/')

And in Python, what is the correct way to open a remote content?

  • There is no correct form, what exists is proper library the specific version of Python, this should help you: http://answall.com/q/56617/3635

  • Sure, it helps. If you want to mark the question...

  • I think you can vary the versions of python, I’ll see for myself. I think there are still some details missing.

3 answers

5


Use urllib2:

import urllib2

def file_get_contents(url):
    return urllib2.urlopen(url).read()
  • 1

    I won’t declare the function under that name, but the solution was nice :)

0

Proxy-free:

import requests

requests.get('/')

Proxy:

import requests

requests.get('/', 
proxies={'http':'http://10.1.1.1:8080', 'https': 'https://10.1.1.1:8080'})

or

import requests
proxies_cfg={
    'http':'http://10.1.1.1:8080', 
    'https': 'https://10.1.1.1:8080',
    'ftp':'http://10.1.1.1:8061',
}
import requests
requests.get('/', proxies=proxies_cfg)

0

This answer will depend on the Python version. The @sergiopereira response works perfectly for Python 2. But in Python 3, for example, I couldn’t find the urllib2, and yes urllib3, which is a little different use.

Behold:

import urllib3

http = urllib3.PoolManager()

response = http.request('GET', '/')

if response.status == 200:
    print(response.data) # resultado da página é exibido aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.