我们在百度搜索时,输入关键词,比如“hello”,URL发生变化,如下:
如果只截取前一部分“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)