Python2.7 网络请求 urllib、urllib2和requests

Python2.7 网络请求 urllib、urllib2和requests

使用 python2.7版本urllib、urllib2和requests发送get请求和post请求

# coding=utf-8
import json
import urllib
import urllib2
import requests

# 发送get请求
def test_urllib_get():
    web_url = 'http://httpbin.org/get'
    data = {
        'name': "xiao",
        'age': 18
    }
    # age=18&name=xiao
    # 转码
    data = urllib.urlencode(data)
    response = urllib.urlopen(web_url + '?' + data, context=headers)
    print response.read()

# 发送post请求
def test_urllib_post():
    web_url = 'http://httpbin.org/post'
    data = {
        'name': "xiao",
        'age': 18
    }
    data = urllib.urlencode(data)
    response = urllib.urlopen(web_url, data=data)
    print response.read()

def test_urllib2_get():
    web_url = 'http://httpbin.org/get'
    data = {
        'name': "xiao",
        'age': 18
    }
    data = urllib.urlencode(data)
    data = web_url + "?%s" % data
    response = urllib2.urlopen(data)
    print response.read()

    # 添加头部
    opener = urllib2.build_opener()
    opener.addheaders = [headers]
    response_opener = opener.open(data)
    print response_opener.read()

def test_urllib2_post():
    web_url = 'http://httpbin.org/post'
    data = {
        'name': "xiao",
        'age': 18
    }
    data = urllib.urlencode(data)
    opener = urllib2.build_opener()
    # 携带头信息
    opener.addheaders = [headers]
    print opener
    response = opener.open(web_url, data=data)
    print response.read()


def test_requests_get():
    data = {
        'name': "xiao",
        'age': 18
    }
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win"
                      "64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"
                      " Chrome/98.0.4758.9 Safari/537.36"
    }
    web_url = 'http://httpbin.org/get'
    response = requests.get(web_url, params=data, headers=headers)
    print response.content


def test_requests_post():
    data = {
        'name': "xiao",
        'age': 18
    }
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win"
                      "64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"
                      " Chrome/98.0.4758.9 Safari/537.36",
    }
    web_url = 'http://httpbin.org/post'
    # "Content-Type": "application/x-www-form-urlencoded",
    # response = requests.post(web_url, data=data, headers=headers)
    # 接受json格式,同 json=data
    response = requests.post(web_url, data=json.dumps(data), headers=headers)
    # 默认"Content-Type": "application/json",
    # response = requests.post(web_url, json=data, headers=headers)
    print response.content


if __name__ == '__main__':
    headers = (
        "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win"
                      "64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"
                      " Chrome/98.0.4758.9 Safari/537.36"
    )
    test_requests_post()

总结:

​ 在使用这些库时候注意Python版本区别,在python2.7中 urllib2 模块直接导入就可以用,在 python3中urllib2被改为urllib.request等问题.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Python中的urllibrequests是两个常用的网络请求库。urllibPython标准库中的模块,提供了一些用于进行网络请求的函数和类,使用简单但功能相对较少。而requests是一个第三方库,功能更丰富,提供了更方便的API来发送HTTP请求和处理响应。 在使用urllib进行GET请求时,可以使用urlopen方法来发送请求并获取响应,通过调用read方法来读取响应数据,然后使用decode方法进行解码。以下是一个示例: import urllib.request response = urllib.request.urlopen('http://www.baidu.com') print(response.read().decode()) 而对于POST请求urllib并没有单独提供相应的函数,而是通过构建Request对象来传递data参数来实现。具体的示例代码如下: import urllib.parse import urllib.request url = 'http://www.someserver.com/cgi-bin/register.cgi' values = {'name': 'Michael Foord', 'location': 'Northampton', 'language': 'Python'} data = urllib.parse.urlencode(values) data = data.encode('ascii') req = urllib.request.Request(url, data) with urllib.request.urlopen(req) as response: the_page = response.read() 另外,requests库提供了更加方便的API来发送GET和POST请求,并处理HTTP响应。以下是一个使用requests库的示例代码: import requests resp = requests.get('http://www.baidu.com') print(resp.text) 可以看到,requests的使用更加简洁明了,通过调用get方法来发送GET请求并获取响应,然后通过text属性来获取响应内容。 综上所述,urllibrequests都是常用的Python网络请求库,根据需求选择适合的库来进行网络请求操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Python 网络请求模块 urllibrequests](https://blog.csdn.net/aifeier1982/article/details/101950448)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Crazy_August

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值