Python爬虫技术 第10节 requests库

requests 是 Python 中非常流行的 HTTP 库,它使得发送 HTTP/1.1 请求变得简单直观。下面我会通过几个实际案例来详细介绍如何使用 requests 库。

1. 发送 GET 请求

最简单的请求类型就是 GET 请求,通常用于获取网页或其他资源。

import requests

# 发送 GET 请求
response = requests.get('https://www.example.com')

# 打印响应的文本内容
print(response.text)

# 打印响应的状态码
print(response.status_code)

2. 添加请求头

许多网站会根据请求头中的 User-Agent 字段来判断请求来源,因此有时我们需要自定义请求头。

headers = {
    'User-Agent': 'My App/0.0.1',
}

response = requests.get('https://www.example.com', headers=headers)

3. 发送 POST 请求

POST 请求通常用于向服务器发送数据,例如登录或提交表单。

data = {
    'username': 'example_user',
    'password': 'example_password',
}

response = requests.post('https://www.example.com/login', data=data)

if response.status_code == 200:
    print("Login successful.")
else:
    print("Login failed.")

4. 上传文件

使用 requests 可以轻松地上传文件。

files = {'file': open('path/to/file.jpg', 'rb')}

response = requests.post('https://www.example.com/upload', files=files)

# 记得关闭文件
files['file'].close()

5. 处理 JSON 数据

requests 自动解析 JSON 响应,使你无需手动解析 JSON 字符串。

response = requests.get('https://api.example.com/data')
json_data = response.json()

# 访问 JSON 数据
print(json_data['key'])

6. 超时设置

可以为请求设置超时时间,防止请求长时间无响应。

try:
    response = requests.get('https://www.example.com', timeout=5)
except requests.Timeout:
    print("The request timed out")
else:
    print("The request did not time out")

7. 处理重定向

requests 默认会自动处理重定向,但也可以选择禁用它。

response = requests.get('https://www.example.com', allow_redirects=False)

if response.is_redirect:
    print("Redirect detected.")
    new_url = response.headers['Location']
    print("New URL:", new_url)

8. 流式下载

对于大文件,可以使用流式下载来避免一次性加载整个文件到内存中。

response = requests.get('https://www.example.com/largefile.zip', stream=True)

with open('localfile.zip', 'wb') as f:
    for chunk in response.iter_content(chunk_size=8192):
        if chunk:  # filter out keep-alive new chunks
            f.write(chunk)

9. 使用会话

requests.Session 对象可以保持某些参数,如 cookies 或 headers,在多个请求之间共享。

session = requests.Session()
session.headers.update({'User-Agent': 'My App/0.0.1'})

# 发送请求
response = session.get('https://www.example.com')

这些只是使用 requests 库的基本示例,实际上它支持更高级的功能,如 SSL/TLS 验证、代理支持、认证等。在编写网络爬虫或 API 客户端时,掌握这些功能将大大提高你的工作效率。

我们可以使用Python来设计一个系统,该系统可以存储、检索和管理大量单词,甚至包括它们的定义、例句和翻译。下面是一个基于Python的单词管理系统的设计和实现的概述。

1. 设计数据库模型

首先,我们需要一个数据库来存储单词信息。这里我们使用SQLite数据库,因为它不需要额外的服务器安装,并且易于集成到Python应用程序中。

import sqlite3

# 创建数据库连接
conn = sqlite3.connect('word_database.db')
c = conn.cursor()

# 创建单词表
c.execute('''CREATE TABLE IF NOT EXISTS words
             (id INTEGER PRIMARY KEY AUTOINCREMENT,
              word TEXT NOT NULL UNIQUE,
              definition TEXT,
              example TEXT,
              translation TEXT)''')

# 提交更改并关闭连接
conn.commit()
conn.close()

2. 实现基本的CRUD操作

接下来,我们需要实现基本的CRUD(创建、读取、更新、删除)操作。

def add_word(word, definition=None, example=None, translation=None):
    conn = sqlite3.connect('word_database.db')
    c = conn.cursor()
    try:
        c.execute("INSERT INTO words (word, definition, example, translation) VALUES (?, ?, ?, ?)",
                  (word, definition, example, translation))
        conn.commit()
    except sqlite3.IntegrityError:
        print("Word already exists.")
    finally:
        conn.close()

def get_word(word):
    conn = sqlite3.connect('word_database.db')
    c = conn.cursor()
    c.execute("SELECT * FROM words WHERE word=?", (word,))
    result = c.fetchone()
    conn.close()
    return result

def update_word(word, definition=None, example=None, translation=None):
    conn = sqlite3.connect('word_database.db')
    c = conn.cursor()
    c.execute("UPDATE words SET definition=?, example=?, translation=? WHERE word=?",
              (definition, example, translation, word))
    conn.commit()
    conn.close()

def delete_word(word):
    conn = sqlite3.connect('word_database.db')
    c = conn.cursor()
    c.execute("DELETE FROM words WHERE word=?", (word,))
    conn.commit()
    conn.close()

3. 用户界面

为了让用户能够与系统交互,我们可以创建一个简单的命令行界面。

def main_menu():
    while True:
        print("\nWord Management System")
        print("1. Add a word")
        print("2. Look up a word")
        print("3. Update a word")
        print("4. Delete a word")
        print("5. Exit")
        
        choice = input("Enter your choice: ")
        
        if choice == '1':
            word = input("Enter the word: ")
            definition = input("Enter the definition: ")
            example = input("Enter an example sentence: ")
            translation = input("Enter the translation: ")
            add_word(word, definition, example, translation)
        elif choice == '2':
            word = input("Enter the word to look up: ")
            print(get_word(word))
        elif choice == '3':
            word = input("Enter the word to update: ")
            definition = input("Enter the new definition: ")
            example = input("Enter a new example sentence: ")
            translation = input("Enter the new translation: ")
            update_word(word, definition, example, translation)
        elif choice == '4':
            word = input("Enter the word to delete: ")
            delete_word(word)
        elif choice == '5':
            break
        else:
            print("Invalid choice. Please try again.")

if __name__ == "__main__":
    main_menu()

4. 扩展功能

除了基本的CRUD操作,你还可以扩展系统以包括更多功能,如单词搜索、随机单词生成、统计信息显示等。

5. 安全性和性能

在生产环境中,你可能需要考虑数据的安全性,例如加密敏感信息,以及优化查询性能,如使用索引。

这个单词管理系统是一个基础的框架,可以根据具体需求进行扩展和定制。例如,可以加入图形用户界面(GUI),或者将其部署到Web上,使其成为一个在线服务。

在这里插入图片描述

如果你想让你的单词管理系统不仅仅局限于本地数据库,而是能够从网络上的资源获取单词定义、例句或翻译,你可以使用requests库来向外部API发送HTTP请求。requests是一个非常流行的Python库,用于发送各种类型的HTTP请求,如GET和POST。

假设你的系统想要从一个在线词典API获取单词的定义,下面是如何使用requests库来实现这一功能的示例:

首先,你需要安装requests库,如果你还没有安装的话,可以通过pip来安装:

pip install requests

然后,在你的代码中,你可以像下面这样使用requests.get()方法来发起GET请求:

import requests

def fetch_definition(word):
    # 假设我们有一个API,它的URL结构如下:
    url = f"https://api.example.com/define?word={word}"
    
    # 发送GET请求
    response = requests.get(url)
    
    # 检查响应状态码是否为200(成功)
    if response.status_code == 200:
        data = response.json()  # 解析JSON响应
        definition = data['definition']  # 假设数据中的定义字段名为'definition'
        return definition
    else:
        return None  # 或者抛出异常,取决于你的错误处理策略

在上述代码中,requests.get(url)会发送一个GET请求到指定的URL。response对象包含了服务器的响应,包括状态码、头信息和响应体。如果响应状态码为200(OK),则表示请求成功,你可以进一步解析响应体,通常是JSON格式的数据,从中提取所需的单词定义。

注意,这只是一个示例,实际的API URL和响应格式可能会有所不同。你需要查阅特定API的文档,了解正确的URL结构和响应数据格式。

现在,你可以将fetch_definition函数整合到你的单词管理系统中,当用户添加或查找单词时,自动从远程API获取定义。例如,修改add_word函数以自动填充定义:

def add_word(word, definition=None, example=None, translation=None):
    if definition is None:
        definition = fetch_definition(word)
    # 其余代码保持不变...

这样,当add_word被调用时,如果没有提供定义,它将尝试从远程API获取定义。

请注意,使用外部API可能会有速率限制、成本问题或其他限制,因此在实际应用中要确保遵循API的使用条款。同时,你还需要处理网络请求可能失败的情况,例如通过捕获requests.exceptions.RequestException异常来增强代码的健壮性。

让我们继续通过代码来具体化上述概念。假设我们使用的是一个虚构的在线词典API,该API返回一个JSON格式的响应,其中包含单词的定义、同义词和反义词。我们将整合requests库来从该API获取数据,并将其存储在我们的本地数据库中。

首先,确保你已经安装了requests库。接下来,我们将修改之前创建的单词管理系统,以实现从API获取单词信息的功能。

import requests
import sqlite3

def fetch_word_info(word):
    url = f"https://api.example.com/words/{word}"
    try:
        response = requests.get(url)
        response.raise_for_status()  # Raises an HTTPError if the HTTP request returned an unsuccessful status code
        data = response.json()
        return data
    except requests.RequestException as e:
        print(f"Error fetching word info: {e}")
        return None

def add_word_from_api(word):
    conn = sqlite3.connect('word_database.db')
    c = conn.cursor()
    
    word_info = fetch_word_info(word)
    if word_info:
        definition = word_info.get('definition')
        synonyms = ', '.join(word_info.get('synonyms', []))
        antonyms = ', '.join(word_info.get('antonyms', []))
        
        # Insert into database
        c.execute("INSERT INTO words (word, definition, synonyms, antonyms) VALUES (?, ?, ?, ?)",
                  (word, definition, synonyms, antonyms))
        conn.commit()
    
    conn.close()

def main_menu():
    # ... previous menu logic ...
    if choice == '1':
        word = input("Enter the word to add: ")
        add_word_from_api(word)
    # ... rest of the menu logic ...

if __name__ == "__main__":
    main_menu()

在这个例子中,我们定义了一个fetch_word_info函数,它负责从API获取单词信息。如果请求成功,它将返回一个字典,其中包含从API接收到的数据;如果请求失败,它将捕获requests.RequestException异常并返回None

add_word_from_api函数使用fetch_word_info来获取单词信息,并将这些信息插入到本地数据库中。我们假设API返回的JSON数据结构如下:

{
    "definition": "A concise statement of the meaning of a word.",
    "synonyms": ["meaning", "interpretation", "explanation"],
    "antonyms": ["misinterpretation"]
}

请注意,为了将多个同义词或反义词存储到数据库中,我们使用逗号分隔的形式将它们合并成一个字符串。在实际应用中,你可能需要根据数据库的设计和API返回的数据格式进行相应的调整。

最后,我们修改了main_menu函数,使得当用户选择“添加单词”选项时,将调用add_word_from_api函数,从而从API获取单词信息并将其保存到数据库中。

这种设计允许你的单词管理系统从网络上动态获取信息,增强了系统的功能和实用性。

  • 13
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值