Python使用urllib和requests发送HTTP请求的方法详解

Written by

in

文章目录
  • Python自带了一个叫urllib的库,就像你手机里自带的短信应用,不需要额外安装。 import urllib.request # 发送一个简单的GET请求 response = urllib.request.urlopen(‘https://www.example.com’) print(response.read().decode(‘utf-8’)) # 读取并解码响应内容
  • 虽然Python自带工具,但requests库就像一款智能邮件应用,让一切变得更加简单直观。 第一步:安装requests pip install requests 第二步:发送各种类型的请求 import requests # 1. 简单的GET请求(获取信息) response = requests.get(‘https://api.github.com’) print(f”状态码: {response.status_code}”) # 200表示成功 print(response.text) # 获取网页内容 # 2. 带参数的GET请求(像在搜索框里输入内容) params = {‘key1’: ‘value1’, ‘key2’: ‘value2’} response = requests.get(‘https://httpbin.org/get’, params=params) print(response.url) # 查看实际请求的URL # 3. POST请求(提交信息,像填写表单) data = {‘username’: ‘user’, ‘password’: ‘pass’} response = requests.post(‘https://httpbin.org/post’, data=data) print(response.json()) # 以JSON格式查看响应 # 4. 自定义请求头(像添加特别说明) headers = {‘User-Agent’: ‘My-Python-App/1.0’} response = requests.get(‘https://httpbin.org/user-agent’, headers=headers) print(response.text)
  • import requests def get_weather(city): # 使用一个免费的天气API(实际使用需要申请API密钥) api_key = “你的API密钥” url = f”http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}” try: response = requests.get(url, timeout=5) # 5秒超时 response.raise_for_status() # 如果请求失败会抛出异常 weather_data = response.json() print(f”{city}的天气: {weather_data[‘weather’][0][‘description’]}”) print(f”温度: {weather_data[‘main’][‘temp’]}K”) except requests.exceptions.RequestException as e: print(f”获取天气信息失败: {e}”) # 使用函数 get_weather(‘Beijing’)
  • 超时设置:总是设置合理的超时时间,避免程序卡死 requests.get(url, timeout=5) 错误处理:使用try-except块捕获可能的异常 try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as e: print(f”请求出错: {e}”) JSON处理:现代API大多返回JSON格式,requests可以直接解析 data = response.json()
  • 简单需求:使用Python内置的urllib 大多数情况:使用requests库,它更简单、更强大 记住设置超时和处理异常 现代Web API大多使用JSON格式,requests可以轻松处理 现在你已经掌握了用Python发送HTTP请求的基本方法!就像学会了写电子邮件一样,你可以开始探索互联网上的各种数据和服务了。 到此这篇关于Python使用urllib和requests发送HTTP请求的方法详解的文章就介绍到这了,更多相关Python发送HTTP请求内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客! 您可能感兴趣的文章: Python发送HTTP请求的不同方式与参数差别详解 使用Python的requests库来发送HTTP请求的操作指南 Python requests库轻松发送HTTP请求的终极指南 python使用requests库实现轻松发起HTTP请求 Python中HTTP请求的全面指南 Python中的HTTP请求库Requests的具体使用
  • 目录
    • 最简单的方式:使用urllib(Python内置)
    • 推荐方式:使用requests库(更简单强大)
    • 实际应用示例:获取天气信息
    • 小贴士和注意事项
    • 总结

    本文介绍了Python中发送HTTP请求的两种方法:内置的urllib库和第三方requests库。urllib提供基础功能,而requests库更简单强大,支持GET/POST请求、参数传递、请求头设置等功能。

    本文通过天气API示例演示了实际应用,并提供了超时设置、错误处理和JSON解析等实用技巧。推荐大多数场景使用requests库,同时强调了异常处理的重要性。这些方法为获取网络数据和与Web服务交互提供了基础工具。

    想象一下,你想要从网上获取一些信息——比如今天的天气、最新的新闻或者一张图片。这就像给网站写一封信,然后等待回信。Python就是你的贴心邮差,帮你轻松完成这个收发过程。

    Python自带了一个叫urllib的库,就像你手机里自带的短信应用,不需要额外安装。

    import urllib.request
    
    # 发送一个简单的GET请求
    response = urllib.request.urlopen('https://www.example.com')
    print(response.read().decode('utf-8'))  # 读取并解码响应内容
    

    虽然Python自带工具,但requests库就像一款智能邮件应用,让一切变得更加简单直观。

    第一步:安装requests

    pip install requests
    

    第二步:发送各种类型的请求

    import requests
    
    # 1. 简单的GET请求(获取信息)
    response = requests.get('https://api.github.com')
    print(f"状态码: {response.status_code}")  # 200表示成功
    print(response.text)  # 获取网页内容
    
    # 2. 带参数的GET请求(像在搜索框里输入内容)
    params = {'key1': 'value1', 'key2': 'value2'}
    response = requests.get('https://httpbin.org/get', params=params)
    print(response.url)  # 查看实际请求的URL
    
    # 3. POST请求(提交信息,像填写表单)
    data = {'username': 'user', 'password': 'pass'}
    response = requests.post('https://httpbin.org/post', data=data)
    print(response.json())  # 以JSON格式查看响应
    
    # 4. 自定义请求头(像添加特别说明)
    headers = {'User-Agent': 'My-Python-App/1.0'}
    response = requests.get('https://httpbin.org/user-agent', headers=headers)
    print(response.text)
    

    import requests
    
    def get_weather(city):
        # 使用一个免费的天气API(实际使用需要申请API密钥)
        api_key = "你的API密钥"
        url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"
        
        try:
            response = requests.get(url, timeout=5)  # 5秒超时
            response.raise_for_status()  # 如果请求失败会抛出异常
            
            weather_data = response.json()
            print(f"{city}的天气: {weather_data['weather'][0]['description']}")
            print(f"温度: {weather_data['main']['temp']}K")
            
        except requests.exceptions.RequestException as e:
            print(f"获取天气信息失败: {e}")
    
    # 使用函数
    get_weather('Beijing')
    

    超时设置:总是设置合理的超时时间,避免程序卡死

    requests.get(url, timeout=5)
    

    错误处理:使用try-except块捕获可能的异常

    try:
        response = requests.get(url)
        response.raise_for_status()
    except requests.exceptions.RequestException as e:
        print(f"请求出错: {e}")
    

    JSON处理:现代API大多返回JSON格式,requests可以直接解析

    data = response.json()
    

    • 简单需求:使用Python内置的urllib
    • 大多数情况:使用requests库,它更简单、更强大
    • 记住设置超时和处理异常
    • 现代Web API大多使用JSON格式,requests可以轻松处理

    现在你已经掌握了用Python发送HTTP请求的基本方法!就像学会了写电子邮件一样,你可以开始探索互联网上的各种数据和服务了。

    到此这篇关于Python使用urllib和requests发送HTTP请求的方法详解的文章就介绍到这了,更多相关Python发送HTTP请求内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!

    您可能感兴趣的文章:

    • Python发送HTTP请求的不同方式与参数差别详解
    • 使用Python的requests库来发送HTTP请求的操作指南
    • Python requests库轻松发送HTTP请求的终极指南
    • python使用requests库实现轻松发起HTTP请求
    • Python中HTTP请求的全面指南
    • Python中的HTTP请求库Requests的具体使用

    站内搜索