ITPub博客

首页 > 大数据 > 数据分析 > Python中urllib和urllib2库的用法

Python中urllib和urllib2库的用法

原创 数据分析 作者:金木大大大 时间:2023-11-24 10:24:31 0 删除 编辑

  在Python中,urllib和urllib2库是用于处理URL的标准库,可以用来发送HTTP请求、处理响应、处理URL编码等。不过需要注意的是,在Python 3中,urllib和urllib2已经合并为urllib库。以下是它们的基本用法:


  使用urllib库发送HTTP请求:


  import urllib.request


  #发送GET请求


  response=urllib.request.urlopen('http://www.example.com')


  html=response.read()


  print(html)


  #发送POST请求


  data=urllib.parse.urlencode({'key':'value'}).encode('utf-8')


  response=urllib.request.urlopen('http://www.example.com',data=data)


  html=response.read()


  print(html)


  使用urllib库处理URL编码:


  import urllib.parse


  #编码


  params={'param1':'value1','param2':'value2'}


  encoded_params=urllib.parse.urlencode(params)


  print(encoded_params)


  #解码


  decoded_params=urllib.parse.parse_qs(encoded_params)


  print(decoded_params)


  使用urllib.request模块设置请求头:


  import urllib.request


  url='http://www.example.com'


  req=urllib.request.Request(url,headers={'User-Agent':'Mozilla/5.0'})


  response=urllib.request.urlopen(req)


  html=response.read()


  print(html)


  在Python 2中,urllib和urllib2库的用法类似,但有一些细微的差别。以下是在Python 2中使用urllib2库的示例:


  import urllib2


  #发送GET请求


  response=urllib2.urlopen('http://www.example.com')


  html=response.read()


  print(html)


  #发送POST请求


  data=urllib.urlencode({'key':'value'})


  request=urllib2.Request('http://www.example.com',data)


  response=urllib2.urlopen(request)


  html=response.read()


  print(html)


  以上是urllib和urllib2库的基本用法,它们是Python中处理URL和发送HTTP请求的重要工具,可以帮助你实现网络数据的获取和处理。


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70032566/viewspace-2997009/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2023-10-12

  • 博文量
    249
  • 访问量
    157736