requests的运用
yt# requests:python实现的简单易用的网址请求模块。
import requests
# 1.请求网址
URL = 'http://www.baidu.com/'
# 请求百度服务器+获取百度服务器响应结果
resp = requests.get(url=URL)
# print(resp)
# 2.查看状态码:告诉我们现在服务器的状态:status_code
# 200:爬虫可用
# 403:爬虫被服务器拒绝了
# 404:资源丢失
# 500:服务器崩溃
print(resp.status_code)
# 3.查看cookie
print(resp.cookies)
# 4.如果页面源码发生了乱码,怎么办?
# 响应结果使用的编码方式默认是ISO-8859-1,它不支持中文。
resp.encoding = 'utf-8'
# 5.查看页面的源代码(字符串形式)
print(resp.text)
# 6.查看页面的源代码(二进制形式)--> 图片、音频、视频等
# b'xxxxxxx' --> 二进制
# print(resp.content)
爬虫伪装
import requests
URL = 'https://www.baidu.com/'
# 伪装爬虫
# User-Agent作用:将爬虫伪装成浏览器
Headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36'
}
resp = requests.get(url=URL, headers=Headers)
if resp.status_code == 200:
resp.encoding = 'utf-8'
print(resp.text)
else:
print(resp.status_code)
requests请求王者荣耀
import requests
URL = 'https://pvp.qq.com/web201605/herolist.shtml'
Headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36'
}
resp = requests.get(url=URL, headers=Headers)
if resp.status_code == 200:
resp.encoding = 'gbk'
print(resp.text)
else:
print(resp.status_code)
# ------------------------------------
def requests_url(href):
Headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36'
}
resp = requests.get(url=href, headers=Headers)
if resp.status_code == 200:
return resp
else:
return resp.status_code
URL = 'https://pvp.qq.com/web201605/herolist.shtml'
result1 = requests_url(URL)
result1.encoding = 'gbk'
print(result1.text)
天行数据
import requests
import json
# api接口中的数据是使用json进行传输的
content = input('请输入一个垃圾:')
# api接口请求地址和参数之间使用?连接,参数以key=value的形式传入,参数和参数之间使用&连接
URL = f'http://api.tianapi.com/lajifenlei/index?key=70fc43dfda9dc06c4da4aa6dcac916d3&word={content}'
# 大部分API接口没有反爬机制。
resp = requests.get(url=URL)
print(resp.text, type(resp.text))
# 序列化:loads()
data = json.loads(resp.text)
print(data, type(data))
# 获取json数据中有用信息
for i in data['newslist']:
print(i['explain'])
图片读取与下载
# 图片读取
with open('1.jpg', 'rb') as f1:
result = f1.read()
# print(result)
# 模拟图片下载(图片二进制写入本地文件)
with open('2.jpg', 'wb') as f2:
f2.write(result)
# 如何下载在线图片、音频、视频?
import requests
# 百度图片链接
URL = 'https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png'
resp = requests.get(url=URL)
print(resp.content)
with open('baidu.png', 'wb') as f3:
f3.write(resp.content)