爬虫之requests

一、基本使用
1、文档:
官方文档:http://cn.python-requests.org/zh_CN/latest/
快速上手:http://cn.python-requests.org/zh_CN/latest/user/quickstart.html
	
	
2、安装
pip install requests

3、response的六个属性以及一个类型
import requests


url = 'http://www.baidu.com'

response = requests.get(url=url)

# 一个类型和六个属性

# response 类型  <class 'requests.models.Response'>
# print(type(response))


# text 属性 以字符串形式来返回网页的源码
# print(response.text)

# encoding 属性 设置响应的编码格式上面返回的网页源码 会乱码
# response.encoding = 'utf-8'
# print(response.text)


# url 属性  返回url地址
# print(response.url)

# content 属性 返回的是二进制数据,类似于 urllib.request  read() 方法
# print(response.content)


# status_code 属性 返回状态码  200 表示正常
# print(response.status_code)


# headers 属性  返回的是响应头
print(response.headers)
二、requests get请求
import requests

url = 'https://www.baidu.com/s?'

headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36'
}

data = {
    'wd': '北京'
}

# url 请求资源路径
# params 请求参数
# kwargs 字典

response = requests.get(url=url, params=data, headers=headers)
content = response.text
print(content)

# 总结:
# 参数使用params 传递 ,不用像 urllib 那样请求对象定制
# 参数无需urlencode的编码
# 请求资源路径中的  ? 可以加也可以不加

三、requests post请求
import requests
import json

url = 'https://fanyi.baidu.com/sug'

headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36'
}

data = {
    'kw': 'eye'
}

# url 请求路径
# data  请参数
# kwargs 字典
response = requests.post(url=url, data=data, headers=headers)

content = response.text

obj = json.loads(content)
print(content)
print(obj)

# 总结:
# post 请求 不需要编解码
# post 请求的参数 是data
# 不需要请求对象的定制
四、代理
import requests


url = 'https://www.baidu.com/s?'

headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36'
}

data = {
    'wd': 'ip'
}

proxy = {
    'http': '121.230.210.31:3256'
}

response = requests.get(url=url, params=data, headers=headers,proxies=proxy)

content = response.text

fp = open('daili.html', 'w', encoding='utf-8')
fp.write(content)
posted @ 2024-08-26 10:35  有形无形  阅读(13)  评论(0)    收藏  举报