Python-爬虫-HTTP协议请求之GET请求
2024-10-07 20:01:48
我们在百度搜索时,输入关键词,比如“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)
最新文章
- C# 版 flvmerge:快速合并多个flv文件
- extracting lines bases a list using awk
- CCActionManager
- vimrc常用配置项
- Adobe Edge Animate –EdgeCommons Log和全局变量设置功能
- Cobar 关系型数据的分布式处理系统
- Java基础---继承、抽象、接口
- GitHub使用(一) - 新建个人网站
- Java数据结构和算法(十五)——无权无向图
- poj2385 Apple Catching(dp状态转移方程推导)
- Android中的指纹识别
- 中文分词算法工具hanlp源码解析
- POJ.2891.Strange Way to Express Integers(扩展CRT)
- (FFT) A * B Problem Plus
- SharePoint Online 创建文档库
- switch to hexo !
- C# 解析 json Newtonsoft果然强大,代码写的真好
- Message: u'$ is not defined' ; Stacktrace
- JAVA实现Excel导入/导出【转】
- 使用 JavaScript 在下拉列表中获取选定的值