不止是Cookie反爬虫

Cookie反爬虫

cookie反爬虫指的是服务器端通过校验请求头中的cookie值来区分正常用户和爬虫程序的手段,这种手段被广泛应用在web应用中。

Cookie反爬虫绕过实战

"""
Cookie 反爬虫绕过实战
示例2:旅游网公告详情页
网站:http://www.porters.vip/verify/cookie/content.html
任务:爬取旅游网公告详情页中地公告标题
"""


import requests
from lxml import etree

url = 'http://www.porters.vip/verify/cookie/content.html'
headers = {'Cookie': 'isfirst=789kq7uc1pp4c'}
#向目标网站发起请求
resp = requests.get(url,headers=headers)
#打印输出状态码
print(resp.status_code)
#如果本次请求地状态码是200,则继续,否则提示失败
if resp.status_code == 200:
    html = etree.HTML(resp.text)
    #根据HTML标签和签名从文档中去除标题
    res = html.cssselect('.page-header h1')[0].text
    print(res)
else:
    print('This request is fial !')



Cookie反爬虫原理和实现

大部分的爬虫程序在默认情况下只请求HTML文本资源,这意味着它们并不会主动完成浏览器保存Cookie的操作,这次的反爬虫正式利用了这个特点。那浏览器又是如何完成Cookie的获取和设置呢?

浏览器会自动检测响应头中是否存在Set-Cookie头域,如果存在,则将值保存在本地,而且往后的每次请求都会自动携带对应的Cookie值,这时候只要服务器端对请求头中的Cookie值进行校验即可。服务器会

猜你喜欢

转载自blog.csdn.net/weixin_43870646/article/details/105179604