Pythonurlopen () function example-Python tutorial

Source: Internet
Author: User
Urlopen (url, dataNone, proxiesNone) creates a class file object that represents a remote url, and then operates on this class file object like a local file to obtain remote data. The parameter url indicates the path of remote data, generally the url. the parameter data indicates the data submitted to the url in post mode. the parameter proxies is used to set the proxy. Let's take a look at some examples.

1. open a webpage to retrieve all the content

The code is as follows:


From urllib import urlopen
Doc = urlopen ("http://www.baidu.com"). read ()
Print doc

2. get the Http header

The code is as follows:


From urllib import urlopen
Doc = urlopen ("http://www.baidu.com ")
Print doc.info ()
Print doc.info (). getheader ('content-type ')

3. use proxy

1. View environment variables

The code is as follows:


Print "" n ". join ([" % s = % s "% (k, v) for k, v in OS. environ. items ()])
Print OS. getenv ("http_proxy ")

2. set environment variables

The code is as follows:


Import OS
OS. putenv ("http_proxy", "http: // proxyaddr: ")

3. use a proxy

The code is as follows:


# Use http://www.someproxy.com: 3128 for http proxying
Proxies = {'http': 'http: // www.someproxy.com: 3128 '}
Filehandle = urllib. urlopen (some_url, proxies = proxies)
# Don't use any proxies
Filehandle = urllib. urlopen (some_url, proxies = {})
# Use proxies from environment-both versions are equivalent
Filehandle = urllib. urlopen (some_url, proxies = None)
Filehandle = urllib. urlopen (some_url)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.