<p>以下是我在学习python-3时收集到的一些笔记:<br/>
我留着它们,以防它们能派上用场或帮助别人。</p>
<h2>如何导入<code>urllib.request</code>和<code>urllib.parse</code>:</h2>
<pre><code>import urllib.request as urlRequest
import urllib.parse as urlParse
</code></pre>
<h2>如何发出GET请求:</h2>
<pre><code>url = "http://www.example.net"
# open the url
x = urlRequest.urlopen(url)
# get the source code
sourceCode = x.read()
</code></pre>
<h2>如何发出POST请求:</h2>
<pre><code>url = "https://www.example.com"
values = {"q": "python if"}
# encode values for the url
values = urlParse.urlencode(values)
# encode the values in UTF-8 format
values = values.encode("UTF-8")
# create the url
targetUrl = urlRequest.Request(url, values)
# open the url
x = urlRequest.urlopen(targetUrl)
# get the source code
sourceCode = x.read()
</code></pre>
<h2>如何发出POST请求(<code>403 forbidden</code>响应):</h2>
<pre><code>url = "https://www.example.com"
values = {"q": "python urllib"}
# pretend to be a chrome 47 browser on a windows 10 machine
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"}
# encode values for the url
values = urlParse.urlencode(values)
# encode the values in UTF-8 format
values = values.encode("UTF-8")
# create the url
targetUrl = urlRequest.Request(url = url, data = values, headers = headers)
# open the url
x = urlRequest.urlopen(targetUrl)
# get the source code
sourceCode = x.read()
</code></pre>
<h2>如何发出GET请求(<code>403 forbidden</code>响应):</h2>
<pre><code>url = "https://www.example.com"
# pretend to be a chrome 47 browser on a windows 10 machine
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"}
req = urlRequest.Request(url, headers = headers)
# open the url
x = urlRequest.urlopen(req)
# get the source code
sourceCode = x.read()
</code></pre>