python进阶(爬虫基础简介)

------------------- http://httpbin.org/get ------ 模拟请求(get/post)传入服务器的Json文件
=================================== get请求 ============================================
{
  "args": {},     ---------- get 请求用 params={ } ,post用 data={ }
  "headers": {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", 
    "Accept-Encoding": "gzip, deflate", 
    "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", 
    "Connection": "close", 
    "Cookie": "_gauges_unique_year=1; _gauges_unique=1", 
    "Host": "httpbin.org", 
    "Upgrade-Insecure-Requests": "1", 
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
  }, 
  "origin": "116.226.241.188", 
  "url": "http://httpbin.org/get"
}
==================================== post请求 ===========================================

一、爬虫的基本知识:

1、爬虫的理解:

         (1)网络爬虫,即Web Spider,网络蜘蛛是通过网页的链接地址来寻找网页的。

2、爬虫的设计过程:

         根据网页的三大特征(框架、样式、行为), 发送请求获取数据,筛选数据保存,数据有url地址,继续(发送请求获取数                       据)。 

3、爬虫的分类:

        通用爬虫:目标、流程(爬取网页 - 存储数据 - 内容处理 - 提供检索/排名服务)、遵循Robots协议。

         聚焦爬虫:与通用搜索引擎爬虫的区别在于: 聚焦爬虫在实施网页抓取时会对内容进行处理筛选,                尽量保证只抓取与需求相关的网页信息。

二、发送请求获取数据(requests包):

  •              ① get请求:requests.get(url,params=None,**kwargs) 
  •                                      特点:1)不加密,安全性低
  •                                                 2)params 请求网址的参数
  •                                                 3)**kwargs 不定长命名参数
  •              ② post请求:reguests.post(url,date=None,json=None,**kwargs)
  •                                      特点:加密,安全性高

          帮助发送请求,这个作为入门的工具还是不错的,对了解一些爬虫的基本理念,掌握爬虫爬取的流程有所帮助。

1、requests安装:

                cmd安装:

                

          anacanda安装:

                

2、基本get请求:

  •                       注意:(1)url是必须的参数,http协议必须要写。
  •                                  (2). text  得到的是 str 类型。
import requests
url2 = 'http://httpbin.org/get'
url3 = 'http://httpbin.org/post'
r = requests.get(url2)
print(r.text)

print(type(r.text))                       <class 'str'>   .text是字符串类型。

r1 = requests.post(url2)
print(r1.text)
import requests
url2 = 'http://www.ibeifeng.com'
===========================================================================================
r = requests.get(url2)
print(r)   --------- <Response [200]>   得到响应对象, 200表示成功
print(type(r))    --------- <class 'requests.models.Response'>  查看返回类型
print(r.status_code)  --------- 查看响应码结果:200;200 :表示响应成功,1** 正在请求,3** 重定向 ,4** 资源错误 ,5** 服务器错误
===========================================================================================
print(r.text)   --------- 获得响应的字符串类型html文本,如果是json文件,需要loads后才可以使用字典。
---------------------- .text 乱码时的处理方法。

 #使用 response.content 把源代码解析成 unicode码, 后面再加上decode("utf-8") 转换成 utf-8编码
url3 = 'https://www.woyaogexing.com/'
r2 = requests.get(url3)
print(r2.text)                      ---------- 乱码。
print(r2.content.decode('utf-8'))   ---------- 以字节形式展示并用utf-8解码得到正常结果(具体要看源网页的编码格式)
===========================================================================================
print(r.encoding)          ---------- gbk 查看编码方式
print(r.cookies)           ---------- 获取缓存
print(r.url)               ---------- 获取当前页面响应的url

3、基本请求get传递参数:

  •                 特点:① 相当于form中input标签提交
  •                            ② get传递参数用 params ,post 传递参数用 data
import requests
url = 'http://httpbin.org/get'
pay = {'name':'yangmi','age':'30'}            # 用字典的格式。相当于将两个键值对传到args对应的value中。
r = requests.get(url,params=pay)      # 传递参数
print(r.text)
print(r.url)             #结果:  http://httpbin.org/get?name=yangmi&age=30 

                                                        

4、基本请求get伪装浏览器:

import requests
url = 'https://www.zhihu.com'
r = requests.get(url)
print(r.text)                   # 被阻拦
=========================================== 伪装浏览器 ================================
dict1 = {
    'name':'zhangsan',
    'age':'20'
}
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
}         #  get 访问添加头文件仿照 浏览器。
r1 = requests.get(url,params=dict1,headers=headers)       # params 添加参数,headers 设置头文件。
print(r1.text)   # 访问成功
print(r1.url)    #  结果:https://www.zhihu.com/signup?next=%2F%3Fname%3Dzhangsan%26age%3D20

5、get请求解析json数据(附加模块json的用法):

(1)简介json模块的方法:

import json
 
data = {
    'name' : 'ACME',
    'shares' : 100,
    'price' : 542.23
}
 
json_str = json.dumps(data)   将python字典对象转化为json字符串。
data = json.loads(json_str)  将json字符串转化为python字典对象

 (2)requests请求json数据的处理方法:

方法一:

import requests
url = 'https://github.com/time.json'
r = requests.get(url)
print(r.text)                -------- 这是str类型
print(r.text['message'])           # 报错
print(r.json())             # requests 内部有一个json解码器,可以将 json 字符串格式转化为 python的对象。
print(r.json()['message'])  # 可以获取字典的values

方法二:

利用插入json模块的方法:

import requests
import json           # 插入json模块
url = 'https://github.com/time.json'
r = requests.get(url)
dict1 = json.loads(r)        # 错误,因为 r 是响应对象,而不是json字符串。
dict2 = json.loads(r.text)   # 将json字符串转化为python字典对象。
print(dict2['message'])

6、利用get下载 音频、图片(需要获取原始套接字响应stream= True):

                  下载音频、图片时注意两点,(1)冒充浏览器:键值对 headers =   (2)‘流’ 键值对: stream = True

                  爬取图片
import requests
url = 'http://wx4.sinaimg.cn/large/67b2eab9ly1flwuchb5vlj20dw0dwdi1.jpg'
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
}
# TODO 增加连接重试次数
from requests.adapters import HTTPAdapter
 
sess = requests.Session()
sess.mount('http://', HTTPAdapter(max_retries=5))
sess.mount('https://', HTTPAdapter(max_retries=5))
sess.keep_alive = False # 关闭多余连接

try:
    text = sess.get(url,headers=headers,stream=True,verify=False,timeout=(5,5)) #  connect 和 read 二者的 timeout,所以是一个数组
    with open('1.jpg','wb') as file:
        for i in text.iter_content(1024*10):
            file.write(i)
    text.close() # 关闭,很重要,确保不要过多的链接
except Exception as e:
    print(e)
            
==========================================================================================
                    爬取音频
import requests
url = 'https://m10.music.126.net/20181112201426/6a0a71e1afe74bf40d48a2598c4cead9/ymusic/3020/0523/bdb1/9b15432eb04a5b4ba66c64409da4b27d.mp3'
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
}
text = requests.get(url,headers=headers,stream=True)
with open('1.mp3','wb') as file:
    for i in text.iter_content(1024):
        file.write(i)
===================================== 第二种方法:存储二进制数据 ==========================
r1=requests.get("http://www.xiaohuar.com/d/file/20190117/07a7e6bc4639ded4972d0dc00bfc331b.jpg",headers=headers)
print(r1.content)
with open("1.jpg",'wb') as file:
    file.write(r1.content)

7、获取网页的cookie:

                   获取 cookie
import requests
url= 'http://www.ibeifeng.com'
a = requests.get(url)
print(a.cookies)

                    向网站发送cookie
import requests
url= 'http://httpbin.org/get'
a = requests.get(url)
print(a.text)
                  第一种
a1 = requests.get(url,cookies={'name':'yangmi'})
print(a1.text)
                   第二种 cookies可以放在hearders中。
a1 = requests.get(url,cookies={'name':'yangmi'})
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
    'cookies':"{'name':'yangmi'}"     # 注意,headers是 str 类型,因此 {'name':'yangmi'} 要加 “”。
}
print(a1.text)
===========================================================================================
模拟登陆 cookies
---- 第一种方式 请求页面获取cookie,然后每次请求带上cookie-----
# 1. 请求登陆页面 dologin.php  使用data参数(FormData) 传入账号密码,然后服务器给我们返回cookie, 使用变量login_status 接收
r=requests.post("http://www.antvv.com/login/dologin.php",data={"uname":"admin","upwd":"123456"})
login_status=r.cookies  # 等同于 浏览器上 保存 cookie
# 2. 请求其他页面的时候, 请求首页,加上 cookies=login_status  也就是,在请求的时候,把cookie带上去,服务器就能识别出来,我们是已经登录的用户了
r1=requests.get("http://www.antvv.com/login/index.php",cookies=login_status)
print(r1.text)

------ 第二种方式 ,直接 模拟一个浏览器------
chrome=requests.session()  # 返回了一个 session 对象,模拟了一个浏览器
chrome.post("http://www.antvv.com/login/dologin.php",data={"uname":"admin","upwd":"123456"})  # 请求登陆页面 ,返回的cookie 会保存在我们模拟的浏览器 chrome上
r=chrome.get("http://www.antvv.com/login/index.php") # 直接使用模拟浏览器 访问 首页,此处不需要再传输cookies 了
print(r.text) # admin 已经登录

三、post请求:   

                      比get 多了 data、files、form    通常操作 用字典的方式。      

1、post请求添加参数(data =):

                                      post访问添加参数为data,get是params

                  

                                     将字典内容传入data的键值对中:

                                                 

2、post请求发送cookie(cookies =):

                             

3、post请求,发送文件(files =)到服务器中:

with open('post_111.txt','wb') as file:
    pass
import requests
url= 'http://httpbin.org/post'
files = {'file': open('post_111.txt','rb')}       ----------- 这里不用 .read()出来,内部自动识别,字典中的key file,代表表单提交时的 input中的name属性 
a = requests.post(url,files=files)
print(a.text)

                                                    

4、post请求,发送json数据:

  •          用法: 处理json数据,引入json模块,json.loads()、json.dumps()。

                                       

5、请求超时与异常处理:

   (1)超时设定timeout:

  •        你可以告诉 requests 在经过以 timeout 参数设定的秒数时间之后停止等待响应。基本上所有的生产
  •               代码都应该使用这一参数。如果不使用,你的程序可能会永远失去响应!                    
import requests            # 导入请求模块
from requests.exceptions import ConnectTimeout,ConnectionError,RequestException   # 导入错误类型
try:
    r = requests.get('http://github.com', timeout=0.1)       # 超时设置
    print(r.status_code)
except ConnectTimeout:
    print('ConnectTimeout')
except ConnectionError:
    print('ConnectionError')
except RequestException as e:
    print(e)
print('运行到此!')

结果:

HTTPSConnectionPool(host='github.com', port=443): Read timed out. (read timeout=0.1)
运行到此!

   (2)异常处理:

            python进阶(异常处理)_name 'psf' is not defined-CSDN博客 ----------------- 异常处理

                 异常处理:
list1=[1,5]
list1[3] = 10
try:
    print(list2)
    print(list1)                
except IndexError as e:          # 索引错误 跳过
    print(e)
except NameError as e:    # 变量未定义错误 跳过
    print(e)
except BaseException as e:    # try代码块错误跳过。
    print(e)

print('a')
print('a')
print('a')

6、proxies 代理:

7、安全SSL认证verify键值对:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Python爬虫进阶涉及到一些高级技术和技巧,以下是一些你可以学习和探索的主题: 1. 多线程和多进程:使用多线程或多进程可以提高爬虫的效率,同时处理多个请求或任务。 2. 使用代理:在爬取网页时,你可能会被网站封禁IP,使用代理可以轮流切换IP地址来规避封禁。 3. 反反爬虫策略:有些网站会采取一些手段防止爬虫,你需要学习如何识别和应对这些策略,比如验证码、页面解密等。 4. 使用Cookie和Session:有些网站会使用Cookie和Session来验证用户身份,你需要学习如何在爬虫中模拟登录和保持会话状态。 5. 使用数据库:将爬取到的数据存储到数据库中可以方便后续的数据分析和处理。 6. 使用框架和库:学习使用一些流行的爬虫框架和库,比如Scrapy、BeautifulSoup、Requests等,可以大大简化爬虫的开发和管理。 7. 高级数据解析和提取:学习使用正则表达式、XPath、CSS选择器等高级技术来解析和提取网页中的数据。 8. 动态网页爬取:学习使用Selenium等工具来爬取动态生成的网页内容,比如通过JavaScript异步加载的数据。 9. 分布式爬虫:学习如何构建分布式爬虫系统,可以提高爬取效率和可靠性。 10. 爬虫的合法性和道德问题:学习了解相关法律法规和伦理道德,确保你的爬虫行为合法合规。 这些都是Python爬虫进阶的一些方向,你可以根据自己的兴趣和需求选择学习的内容。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值