Python-爬虫-HTTP协议请求之GET请求

我们在百度搜索时,输入关键词,比如“hello”,URL发生变化,如下:

https://www.baidu.com/s?wd=hello&rsv_spt=1&rsv_iqid=0xfc1746f10002f457&issp=1&f=8&rsv_bp=0&rsv_idx=2&ie=utf-8&tn=baiduhome_pg&rsv_enter=1&rsv_sug3=6&rsv_sug1=6&rsv_sug7=100&rsv_t=bfb1srfxPDC%2B3vVQ8VIkfcg4Yus9EaBJZmHlVn5upgnCTMv99iZYH9iJSX3nVzXYdpeC

如果只截取前一部分“https://www.baidu.com/s?wd=hello”,搜索效果是相同的,wd=后面跟的就是我们要搜索的关键词。

因此,我们可以通过这个构造GET请求。

import urllib.request

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

print(data)
with open('1.html', 'wb') as f:
    f.write(data)

也可以用另一种简化一点的方法,原理是相同的:

from urllib.request import urlopen

keywd = 'hello'
url = 'http://www.baidu.com/s?wd=' + keywd
html = urlopen(url).read()

with open('1.html', 'wb') as f:
    f.write(html)

这样保存到1.html的,就是我们想要的搜索结果网页。

但是对于汉字搜索,上面的程序就是报错,这是由于编码问题造成的。对于这个问题,可以利用urllib.parse中的quote解决,具体如下:

from urllib.request import urlopen
from urllib.parse import quote

keywd = quote('你好')

url = 'http://www.baidu.com/s?wd=' + keywd
html = urlopen(url).read()

with open('1.html', 'wb') as f:
    f.write(html)

 

posted on 2017-05-09 17:28  可豆豆  阅读(5997)  评论(0编辑  收藏  举报

导航