公式文書:http://cn.python-requests.org/zh_CN/latest/
llib.request要求リターンページ
ulbrquettは、最も単純なアプリケーションはurlie.requet.urlopenで、以下の機能を使用します。
urllib. request.urlopen(ur1[,data[, timeout[, cafile[, capath[, cadefaultl,context] ] ] ] ]
公式文書によると、urllib.request.urlopenは、主にHTTPプロトコルで使用されるURL HTTP、HTTPS、FTPプロトコルを開くことができます。
検証に関連するパラメータは、あまり一般的にCAをアイデンティティとしている始まります。
、通常はあまり使用によるURLの記事を提出することは、データ・パラメータの道であるとき。
最も一般的にのみURLとタイムアウトパラメータに使用します。
URLパラメータは、ネットワークに出願アドレス(フルアドレス、プロトコル名は、タイムアウトhttp://192.168.1.1:80),timeoutなどの後端ポートニーズを、遠位端を要します。
- 関数の戻りオブジェクトには、3つの追加の使用を持っています
- ()関数は、一般にリダイレクトURLケースのgetURLで使用される応答のURL情報を返します。
- 情報()関数は、基本的な情報の応答を返します。
- getCode()関数は、応答ステータスコードを返します。最も一般的なコードが正常にページサーバ200に返され、404要求されたページが存在しない場合、サーバー503は、一時的に利用できません。
[実施例D]
import urllib.request
__author__ = 'ling.'
def linkBaidu():
#网址
url = 'http://www.baidu.com'
try:
#通过urllib发起的请求,会有一个默认的header:Python-urllib/version,指明请求是由urllib发出的,所以遇到一些验证user-agent的网站时,我们需要伪造我们的headers
#伪造headers,需要用到urllib.request.Request对象
req = urllib.request.Request(url, headers=headers)
#向指定的url发送请求,并返回服务器响应的类文件对象; 设置timeout参数,如果请求超出我们设置的timeout时间,会跑出timeout error 异常。
response = urllib.request.urlopen(req,timeout=3)
# response.read() 接收json数据; decode 解码方式为utf-8
result = response.read().decode('utf-8')
except Exception as e:
print("网络地址错误")
exit()
with open('baidu.txt', 'w') as fp:
fp.write(result)
print("获取url信息 : response.geturl() : %s" %response.geturl())
print("获取返回代码 : response.getcode() : %s" %response.getcode())
print("获取返回信息 : response.info() : %s" %response.info())
print("获取的网页内容已存入当前目录的baidu.txt中,请自行查看")
ピュアコード
import urllib.request
__author__ = 'ling.'
def linkBaidu():
url = 'http://www.baidu.com'
try:
req = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(req,timeout=3)
result = response.read().decode('utf-8')
except Exception as e:
print("网络地址错误")
exit()
with open('baidu.txt', 'w') as fp:
fp.write(result)
print("获取url信息 : response.geturl() : %s" %response.geturl())
print("获取返回代码 : response.getcode() : %s" %response.getcode())
print("获取返回信息 : response.info() : %s" %response.info())
print("获取的网页内容已存入当前目录的baidu.txt中,请自行查看")