我们在百度搜索时,输入关键词,比如“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)

最新文章

  1. C# 版 flvmerge:快速合并多个flv文件
  2. extracting lines bases a list using awk
  3. CCActionManager
  4. vimrc常用配置项
  5. Adobe Edge Animate –EdgeCommons Log和全局变量设置功能
  6. Cobar 关系型数据的分布式处理系统
  7. Java基础---继承、抽象、接口
  8. GitHub使用(一) - 新建个人网站
  9. Java数据结构和算法(十五)——无权无向图
  10. poj2385 Apple Catching(dp状态转移方程推导)
  11. Android中的指纹识别
  12. 中文分词算法工具hanlp源码解析
  13. POJ.2891.Strange Way to Express Integers(扩展CRT)
  14. (FFT) A * B Problem Plus
  15. SharePoint Online 创建文档库
  16. switch to hexo !
  17. C# 解析 json Newtonsoft果然强大,代码写的真好
  18. Message: u'$ is not defined' ; Stacktrace
  19. JAVA实现Excel导入/导出【转】
  20. 使用 JavaScript 在下拉列表中获取选定的值

热门文章

  1. redis-config.properties属性资源文件
  2. thinkphp整合后台模板
  3. Shiro学习(13)RememberMe
  4. Linux环境安装PHP链接SQLserver2008
  5. CSS中各种百分比(%)
  6. Useful code snippets with C++ boost
  7. base64和Xxtea的加密和解密
  8. ajax url地址
  9. 20140724 菜单制作:制表位(段落->制表位->)
  10. tomcat服务器和HTTP协议