python访问抓取网页常用命令总结

python访问抓取网页常用命令

简单的抓取网页:

import urllib.request  
url="http://google.cn/" 
response=urllib.request.urlopen(url)  #返回文件对象
page=response.read() 

直接将URL保存为本地文件

import urllib.request  
url="http://google.cn/" 
response=urllib.request.urlopen(url)  #返回文件对象
page=response.read() 

POST方式:

import urllib.parse 
import urllib.request 
 
url="http://liuxin-blog.appspot.com/messageboard/add" 
 
values={"content":"命令行发出网页请求测试"} 
data=urllib.parse.urlencode(values) 

#创建请求对象 
req=urllib.request.Request(url,data) 
#获得服务器返回的数据 
response=urllib.request.urlopen(req) 
#处理数据 
page=response.read() 

GET方式:

import urllib.parse 
import urllib.request 
 
url="http://www.google.cn/webhp" 
 
values={"rls":"ig"} 
data=urllib.parse.urlencode(values) 
 
theurl=url+"?"+data 
#创建请求对象 
req=urllib.request.Request(theurl) 
#获得服务器返回的数据 
response=urllib.request.urlopen(req) 
#处理数据 
page=response.read() 

有2个常用的方法,geturl(),info()

geturl()的设置是为了辨别是否有服务器端的网址重定向,而info()则包含了一系列的信息。

中文问题的处理,会用到 encode()编码 dencode()解码:

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持

相关文章

在前一篇博客中我们介绍了加侧旋的乒乓球弧圈技术的模拟,本...
在近期conda的版本更新中,有可能会删除路径下的_sysconfigd...
本文主要展示了一些lambda表达式的使用示例,通过这些示例,...
本文通过对比Jax和Numpy计算Normalized Hamming Distance的过...
我们知道GPU加速在可并行化程度比较高的算法中,能够发挥出比...
Numpy这个库在Python编程中非常的常用,不仅在性能上补足了P...