栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python爬虫入门

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python爬虫入门

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)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/875880.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号