天天看点

python爬虫3之http get请求模拟

如果要进行客户端和服务端的消息传递,我们可以使用Http协议请求进行。

GET请求会通过URL网址传递信息比如在百度上查找一个关键字hello,使用爬虫自动实现这个过程。

思路如下:

(1)构建对应的url地址,该URL地址包含GET请求的字段名和字段内容等信息,并且URl满足get请求的格式,即“http://网址? 字段名1=字段内容&字段名2=字段内容2“

(2)以对应的URL为参数,构建Request对象。

(3)通过urlopen()打开构建的request对象。

(4)按需求进行之后的操作。

import urllib.request
keywd="hello"
url="http://www.baidu.com/?wd="+keywd
req=urllib.request.Request(url)
data=urllib.request.urlopen(req).read
           

但是当检索的内容是中文时,会出现编码错误:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 9-10: ordinal not in range(128)
           

此时可以对代码进行修改:

import urllib.request
keywd="天才"
key_code=urllib.request.quote(keywd)
url="http://www.baidu.com/?wd="+key_code
req=urllib.request.Request(url)
data=urllib.request.urlopen(req).read