Crawler Learning (02): Basics of requests module

1. Introduction to the requests module

  1. Function: simulate a browser to send a request.
  2. Installation: Go to the local terminal and enter the following code to install
pip install requests
  1. Guide package:
#  使用requests的模块的时候需要导入模块
import requets
  1. Two ways to send requests
  • GET: Display submission, you can directly see the data submitted by get in the address bar, and the browser directly enters the location of the URL (this time the request is get)
  • POST: implicit submission, the data submitted by post is generally invisible in the address bar. Form (login, registration, password)
#  get()
#  get请求参数是放在Query String Parameters里面的,可以直接放在url里面
#  参数1: 需要发送的url地址, 参数2: 携带的参数,get请求一般直接放在url里面,后面的参数看情况而加,常见的就是添加请求头的信息,进行UA伪装
resp = requests.get(url, params=None, **kwargs)
#  post()  与get类似,传入的参数是data而不是params
#  post请求参数是放在From Data里面的,from data里的参数是不放在url里面的
resp = requests.post(url, data=None, **kwargs)
'''
需要注意的是:
有时候请求参数是放在request payload里面的,而这类参数需要用json来接收 在请求头中必定跟着application/json
#  在添加请求头中必须加入Content-Type: application/json
'''
headers = {
    
    
	'Content-Type': 'application/json'
}
url = 'xxx'
data = {
    
    
	'xxx': 'xxx'
}
#  方法一
#  如果使用方法一,需要在headers中加'Content-Type': 'application/json'
#  json.dumps 转换为json格式
resp = requests.post(url, json.dumps(data), headers=headers)

#  方法二
#  或者直接json={字典}也是可以的
resp = requests.post(url, json=data, headers=headers)
  1. Status code (status code of HTTP protocol):
200 系列 :一般指的是你当前本次和服务器进行通信没有问题

300 系列: 一般指重定向,注意在响应头上能看到location字样
我们在写爬虫的时候,基本上不用管302,因为requests可以自动帮你完成这个重定向的动作

404 系列: 走丢了,你的url不存在,在服务器上人家没有办法给你想要的内容
403 系列: 一般都是被风控拦截了

500 系列: 服务器内部出现了错误
浏览器上啥事没有,你的程序一跑就500,基本上就是你给的参数有问题,让服务器无法正常的工作

当遇到time out(超时)的时候,可以使用下面循环
for i in range(10):
	try:
		发请求
		break
	except Exception as e:
		print('出错了')

Two, requests actual combat

1. Search by keyword (sogou)

import requests  # 导入包
# get url上的参数是Query String Parameters
n = input("请输入一个关键词:")  # 输入一个关键词
url = f'https://www.sogou.com/web?query={
      
      n}'  # 访问网址
#  请求头(UA伪装)
header = {
    
    
    "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36"
}
resp = requests.get(url, headers=header)  # 返回的数据
print(resp.text)  # 打印文本

2. Baidu translation (Post exercise)

'''
    抓取百度翻译
    需求
    1. 首先进入到百度翻译 https://fanyi.baidu.com
    2. 接着F12打开XHR获取动态加载页面
    3. 在翻译框中输入一个单词
    4. 查看数据包,并截取自己想要的数据
    5. 获取数据
 '''
import requests
url = "https://fanyi.baidu.com/sug"  # 抓包里看到的
# post请求参数是放在From Data里面的,from data里的参数是不放在url里面的
# From Data ==> data
# Query String Parameters ==> url
key = input('请输入单词: ')
data = {
    
    
    "kw": key  # 抓包里看到的
}
resp = requests.post(url, data)  # post抓包里看到的
# print(resp.text)  # 返回的是json字符串

# 处理json字符串.方案一
import json
dic = json.loads(resp.text)
for i in dic['data']:
    name = i['k']
    mean = i['v']
    print(f'{
      
      name}|{
      
      mean}')
print('='*30)  # 方便观察上下两种方案是否输出相同
# 方案二 直接将返回结果处理成json
# print(resp.text) # 最好在这里确定是否为json字符串
dic1 = resp.json() # 前提:服务器返回的必须是json字符串才可以
for i in dic1['data']:
    name = i['k']
    mean = i['v']
    print(f'{
      
      name}|{
      
      mean}')
# 两者返回结果一样

# resp.text # 单纯,拿文本,html,json =>字符串
# resp.json() # 不单纯,只能拿json =>字典

3. Douban movie top250 (requests advanced)

'''
方法论:
任何一个网站,第一件事,观察你要的东西在不在页面源代码中
如果在
    直接请求url即可
若不在
    抓包工具观察,数据究竟是从哪个url加载进来的
'''
# 题目需求
# 进入豆瓣电影 https://www.douban.com/
# 点击电影栏
# 进入排行榜,右边随便选择一个电影的类型
# 获取电影的内容数据(名字,演员等等)

# 方案一 参数太长,看起来费劲
# import requests
# url = 'https://movie.douban.com/j/chart/top_list?type=24&interval_id=100%3A90&action=&start=0&limit=20'
# header = {
    
    
#     "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36"
# }
# resp = requests.get(url,headers=header)
# print(resp.json())

# 方案二
# 1 获取url中?之前的url
# 2 在Payload中获取参数
import requests
url = 'https://movie.douban.com/j/chart/top_list'
parse = {
    
    
    "type": "24",
    "interval_id": "100:90",
    "action": "",
    "start": "0",
    "limit": "20"
}
header = {
    
    
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36"
}
# 发送get请求,将参数带进去,params传参
resp = requests.get(url, params=parse, headers=header)
print(resp.json())  # 转换成json格式
print(resp.request.url) # 可以发现和方案一是一样的url

4. Image download (exe, rar, zip, etc.)

import requests
url = 'https://img9.doubanio.com/view/photo/s_ratio_poster/public/p2797313535.jpg'
resp = requests.get(url)
content = resp.content  # . 相当于'的' content 表示拿到的是字节
# with open打开一个文件, ‘wb’: 以二进制的形式写入
with open('hhh.jpg','wb') as f:
    f.write(content)  # write 写入

5. Douban movie storage

'''
需求
https://movie.douban.com/typerank?type_name=%E7%88%B1%E6%83%85&type=13&interval_id=100:90&action=
尝试抓取前`100`部电影的`名称`, `分数`, `封面图的url`
'''
import requests
#  with open 打开一个文件,如果不存在,则自动创建
#  w 写入
with open('电影排名.txt','w') as f:
    for num in range(5):
        start = num*20
        url = 'https://movie.douban.com/j/chart/top_list'
        params = {
    
    
            "type": "13",
            "interval_id": "100:90",
            "action": "",
            "start": start,
            "limit": "20"
        }
        header = {
    
    
            """Cookie""": """ll="118173"; bid=_Wl9BaS0eKI; gr_user_id=909d0c5b-e83f-4391-80e5-5259e3c545d6; ap_v=0,6.0""",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36"
        }
        resp = requests.get(url, params=params, headers=header)
        dic = resp.json()
        # print(dic)
        for i in dic:
            rank = i['rank']
            title = i['title']
            score = i['score']
            img = i['cover_url']
            # f.write(rank)
            # f.write("|")
            # f.write(title)
            # f.write("|")
            # f.write(score)
            # f.write("|")
            # f.write(img)
            f.write(str(rank) + "|" + title + "|" + score + "|" + img + "\n")
            # print(f'第{rank}部:{title},评分:{score} | 封面图地址: {img}')
        print(f'第{
      
      i+1}页下载完成!!!')
print("Over!!!!")

3. Summary of requests

  1. requests.get()To send a get request, the request parameters can be placed directly urlbehind ?or in a dictionary and passed to params.
  2. requests.post()Send a post request, the request parameters should be placed 字典in it, and passed todata
  3. Request PayloadThe parameters need to be dataconverted tojson
  4. resp.textReceive 文本, the essence is to resp.contentcarry out decode()the result. str
  5. resp.json()Receive 响应中的json字符串, 并将其处理成字典dict|list
  6. resp.contentreceive 字节bytes

Guess you like

Origin blog.csdn.net/m0_48936146/article/details/127231408