avatar

刘刚刚的blog

采菊东篱下,悠然见南山🦥

  • 首页
  • 大模型应用
  • 常用软件/工具
  • Halo
  • 关于
Home python爬虫-1.request模块的使用
文章

python爬虫-1.request模块的使用

Posted 2020-08-5 Updated 2024-12- 10
By Administrator
7~10 min read

通过request模块,可以发起http请求获取响应内容,在pyhton中进行进一步的处理


爬虫简介

爬虫通过模拟浏览器或其他应用发送请求,获取到数据。

  1. 模拟发送请求(requests、selenium),包括:请求地址,请求头,请求体,请求方法

  2. 拿到响应,包括:json、xml、html、其他加密格式等

  3. 提取有用的信息并存放到数据库中,包括:文本、exccel、mysql、redis、mongodb

request 模块的使用

  1. 基本使用

    #安装 pip3 install requests
    
    import requests
    # 设置头
    header = {
         # 用户的浏览器信息
         'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36',
         # 用户的访问来源信息,一般用来防盗链
         'referer': 'https://www.mzitu.com/225078/2'
     }
    
    # 发起获取图片的请求,获取到二进制内容
    res1 = requests.get('https://i3.mmzztt.com/2020/03/14a02.jpg', headers=header)
    
    # 将二进制内容写入到文件中
    with open('a.jpg', 'wb')as f:
       for line in res1.iter_content():
             f.write(line)
  2. GET请求中携带数据的方式

    # 链接中直接携带
    res=requests.get('https://www.baidu.com/s?wd=shuta',headers=header)
    # 使用params参数
    res=requests.get('https://www.baidu.com/s',headers=header,params={'wd':'shuta'})
  3. 发送POST请求

    res=requests.post('http://127.0.0.1:8000/index/',data={'name':'lqz'})
    res=requests.post('http://127.0.0.1:8000/index/',json={'age':1,},)
  4. 携带COOKIE的方式

    #方式1:header中携带
    header = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36',
         'cookie':'key=asdfasdfasdfsdfsaasdf;key2=asdfasdf;key3=asdfasdf'
    }
     res=requests.get('http://127.0.0.1:8000/index/',headers=header)
    
    #方式2:使用参数 
    res=requests.get('http://127.0.0.1:8000/index/',headers=header,cookies={'key':'asdfasdf'})
    
    #方式3:自动携带
    session=requests.session()
    res=session.post('http://127.0.0.1:8000/index/') 
  5. 上传文件

    res = requests.post('网址',files = {'myfiles':open('文件','rb')})
  6. response对象

    # 响应的文本
    print(respone.text)  
    # 响应体的二进制
    print(respone.content)  
    # 响应状态码
    print(respone.status_code)
    # 响应头
    print(respone.headers) 
    # cookie
    print(respone.cookies)   
    #  把cookie转成字典
    print(respone.cookies.get_dict()) 
    # key和value
    print(respone.cookies.items())  
    # 请求的url
    print(respone.url)      
    # 如果被重定向那么可以获取到重定向前的地址
    print(respone.history)   
    # 响应的编码方式
    print(respone.encoding)  
    # 如果为文件,那么可以保存
    respone.iter_content()  
    for line in respone.iter_content():
        f.write(line)
    
  7. 处理编码问题

    res=requests.get('http://www.autohome.com/news')
    
    # 指定编码格式
    res.encoding='gb2312'
    # 自动根据html中指定的编码进行处理
    res.encoding=res.apparent_encoding
    print(res.text)
  8. 解析json

    import json
    
    response = requests.post(网址)
    #方式一:
    res = json.loads(response.txt)
    #方式二:
    res = response.json()
  9. 使用SSL

    rsponse = request.get('网站',cert=('/path/server.crt','/path/key'))
  10. 使用代理

    response = request.get('网址',proxies={'http':'ip:端口',}) 
  11. 设置超时时间

    # 时间为秒不需要写单位,
    response = requests.get('网址',timeout=时间)
  12. 捕捉异常

    from requests.exceptions import *
    try:
        response = requsets.get('网址')
    except ReadTimeout:
        pass
    except exceptions
        pass

python
python
License:  CC BY 4.0
Share

Further Reading

Apr 21, 2025

Typing

类型注释让python 有了更好的编辑器提示功能。 基础使用 对函数参数和返回值,进行类型注释 def surface_area_of_cube(edge_length: float) -> str:    return f"The surface area of the cube is {6 *

Feb 25, 2025

python多进程多线程下的计数及日志打印

注意点: 需要保证在多进程内的进程锁是同一个 需要保证在单进程中的多线程内线程锁是同一个 # logger.py import multiprocessing import threading ​ ​ class Logger_test:    def __init__(self, process

Dec 25, 2022

python-迭代器、生成器、协程

迭代器 Python中当容器对象提供了对迭代的支持时,可以通过container.__iter__()来返回一个迭代器对象。 迭代器需要支持以下两个方法,这两个方法共同构成了迭代器协议: iterator.__iter__() 该方法返回迭代器本身,这个方法是配合for和in使用所必须的。 iter

OLDER

7.python基础——模块

NEWER

mysql必知必会

Recently Updated

  • 文本切分-语义分割(Semantic Chunking)
  • dify 并发配置优化
  • Typing
  • 大模型返回中json_schema与json_mode的区别
  • Async

Trending Tags

Halo 运维 postgresql 设计模式 linux就该这么学 nas rag odoo python 文本切分

Contents

©2025 刘刚刚的blog. Some rights reserved.

Using the Halo theme Chirpy