爬虫(二)--requests模块

一、requests模块

(一)get请求

1.步骤

  1. 导包

    import requests
    
  2. 确定请求的url

    base_url = ''
    
  3. 发送请求,获取响应

    response = requests.get(
    	url = base_url,
    	headers = {},    # 请求头字典
    	params = {},    # 请求参数字典
    )
    

2.response对象

这个对象包含的内容有以下几个

  1. 状态码

    response.status_code
    
  2. 响应头

    response.headers['Cookie']
    
  3. 响应正文

    获取字符串类型的响应正文:

    response.text
    

    获取bytes类型的响应正文:

    response.content
    

    响应正文字符串编码:

    response.encoding
    

响应内容的乱码问题:

当我们用response.text获取字符串的响应正文的时候,有时候会出现乱码

原因是:response.encoding的默认指定编码有误

解决方法:

  1. 手动指定

    response.encoding = 'utf-8'
    
  2. 解码

    response.content.decode('utf-8')
    

3.get请求项目类别

1.没有请求参数的,我们只需要添加请求头,封装User-Agent这个请求头就可以了

比如百度和百度产品两个项目

百度产品

# 1.导包
import requests
# 2.确定url
base_url = 'https://www.baidu.com/more/'
# 3.发送请求,获取响应
response = requests.get(base_url)
# 查看页面内容
# print(requests.text)
# print(requests.encoding)
print(response.status_code)    # 状态码
print(response.headers)    # 响应头
print(type(response.text))    # <class 'str'>
print(type(response.content))    # <class 'bytes'>

'''
解决乱码
'''
# 1
# response.encoding = 'utf-8'
# print(response.text)
# with open('index.html','w',encoding='utf-8') as fp:
#     fp.write(response.text)

# 2
with open('index.html','w',encoding='utf-8') as fp:
    fp.write(response.content.decode('utf-8'))

百度

import requests

base_url = 'https://www.baidu.com'
# 封装请求头
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
}
with requests.get(base_url,headers = headers) as response:
    if response.status_code == 200:
        with open('baidu.html','w',encoding='utf-8') as fp:
            fp.write(response.content.decode('utf-8'))
    else:
        print('error')

2.带请求参数的,基础url就是?之前包括?的部分,需要设置请求头和请求参数字典

比如新浪新闻这个项目

import requests

# 携带参数的get请求,基础url是问号之前包括问号的部分
base_url = 'https://search.sina.com.cn/?'
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
}

q=input('请输入想要查询的内容:')

params = {
    'q': q,
    'c': 'news',
    'from': 'channel',
    'ie': 'utf-8'
}
response = requests.get(base_url,headers = headers,params=params)
with open('sina_news.html','w',encoding='gbk') as fp:
    fp.write(response.content.decode('gbk'))

3.分页

方法:

  1. 找到分页的规律,一般是通过params参数中的其中一个参数来控制的
  2. 找到这个参数每一页的规律
  3. 用for循环来请求每一页的内容

比如百度贴吧这个项目

import requests
import os

base_url = 'http://tieba.baidu.com/f?'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
}
kw = 'java'
dirname = './tieba/'+kw+'/'
if not os.path.exists(dirname):
    os.makedirs(dirname)
for i in range(10):
    params = {
        'kw': kw,
        'ie': 'utf-8',
        'pn': str(i*50)
    }
    response = requests.get(base_url,headers = headers,params=params)
    with open(dirname+kw+'%s.html'%(i+1),'w',encoding='utf-8') as fp:
        fp.write(response.content.decode('utf-8'))

(二)post请求

发送请求

response = requests.post(
	url,
	headers = {},    # 请求头字典
	data = {}    # 请求数据字典
)

post请求一般得到的响应内容是json数据。

json数据本质上就是字符串,处理json数据用到的模块是json模块。

json模块的常用方法:

json.dumps(python的list或者dict)    # 返回值为json字符串
json.loads(json字符串)    # 返回值为python的list或者dict

使用response.json(),可以直接将响应内容的json字符串转换成python的list或者dict。

1.基础post请求

百度翻译项目

import requests

url = 'https://fanyi.baidu.com/sug'
kw = 'origin'
data = {
    'kw':kw,
}
headers = {
    'content-length': str(len(str(data))),
    'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'origin': 'https://fanyi.baidu.com',
    'referer': 'https://fanyi.baidu.com/?aldtype=16047',
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
    'x-requested-with': 'XMLHttpRequest'
}
response = requests.post(url,headers=headers,data=data)
json_str = response.text
json_data = response.json()
# print(type(json_str))    # <class 'str'>
# print(json_str)
# print(type(json_data))    # <class 'dict'>
# print(json_data)
result = ''
for data in json_data['data']:
    result += data['k']+':\n'+data['v']+'\n'
print(result)

2.问题

post请求的请求参数换了,就请求不到了

这就需要解决改变的请求参数

思路:

  1. 对比。对比两次请求的data字典,找到不一样的参数

  2. 找到这些参数的生成原理,并手动生成它们

    可能找到这些参数的位置:

    • 页面中,这种情况的参数,都是固定写死的
    • js中动态生成的参数
    • 通过ajax获取

3.有道词典项目(js中动态生成参数)

import time,random,hashlib,json
import requests

url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'

def get_md5(value):
    md5 = hashlib.md5()
    md5.update(value.encode())
    return md5.hexdigest()
i = 'word'
salt = str(int(time.time()*1000)) + str(random.randint(0,10))
sign = get_md5("fanyideskweb" + i + salt + "n%A-rKaT5fb[Gy?;N5@Tj")
ts = str(int(time.time()*1000))
data = {
    'i': i,
    'from': 'AUTO',
    'to': 'AUTO',
    'smartresult': 'dict',
    'client': 'fanyideskweb',
    'salt': salt,
    'sign': sign,
    'ts': ts,
    'bv': 'f0325f69e46de1422e85dedc4bd3c11f',
    'doctype': 'json',
    'version': '2.1',
    'keyfrom': 'fanyi.web',
    'action': 'FY_BY_REALTlME'
}
headers = {
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'Accept-Encoding': 'gzip, deflate',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    'Connection': 'keep-alive',
    'Content-Length': str(len(str(data))),
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'Cookie': '_ntes_nnid=a34e4f9a3febc07732be65da730cc12c,1571726549684; OUTFOX_SEARCH_USER_ID_NCOO=1297033622.5178812; OUTFOX_SEARCH_USER_ID="[email protected]"; _ga=GA1.2.1132435346.1572169065; _gid=GA1.2.1708709462.1572169065; JSESSIONID=aaaUk11nUld4J6hzmyr4w; ___rl__test__cookies=1572249660634',
    'Host': 'fanyi.youdao.com',
    'Origin': 'http://fanyi.youdao.com',
    'Referer': 'http://fanyi.youdao.com/',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
    'X-Requested-With': 'XMLHttpRequest'
}
response = requests.post(url,headers = headers,data = data)
json_data = response.json()
for mean in json_data['smartResult']['entries']:
    print(mean)
发布了92 篇原创文章 · 获赞 12 · 访问量 5735
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章