第9节-学会使用cookie-互动练习-“解密加密文章”

全代码分析

第一部分:

import requests
from bs4 import BeautifulSoup

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

#header可以从All或者XHR中任意一条中找到,都是一样的
在这里插入图片描述
第二部分:

def sign_in():#带参数请求登陆
    url_login = 'https://xiaoke.kaikeba.com/example/wordpress/wp-login.php?action=postpass'
    data_login = {'post_password':'xiaoke123',
                  'Submit': '提交'
}    
    res=session.post(url_login, headers=headers, data=data_login)
    print(res.status_code)

url_login和data_login都是第一次输入密码后登陆进去的页面中找到的
在这里插入图片描述
在这里插入图片描述
第三部分

def get_content():
    url='https://xiaoke.kaikeba.com/example/wordpress/2019/11/07/互联网圈炸锅啦!有人要帮你加薪啦!/'
  #url='https://xiaoke.kaikeba.com/example/wordpress/2019/11/07/%e4%ba%92%e8%81%94%e7%bd%91%e5%9c%88%e7%82%b8%e9%94%85%e5%95%a6%ef%bc%81%e6%9c%89%e4%ba%ba%e8%a6%81%e5%b8%ae%e4%bd%a0%e5%8a%a0%e8%96%aa%e5%95%a6%ef%bc%81/'
    res_article = session.get(url,headers=headers)
    # 获取数据
    print(res_article.status_code)
    #判断获取结果是否为空
    bs_article = BeautifulSoup(res_article.text,'html.parser')
    #解析数据
    article= bs_article.find('div',class_='entry-content').text
    print(article)

在这里插入图片描述

  • 因为html里面有我们想要的内容,所以用bs解析,url直接从顶端接口处获得,两种url是一样的
  • res_article=session.get(), 不能使用requests.get(), 否则会出现:

这是一篇受密码保护的文章,您需要提供访问密码:
密码:

说明session可以保存之前登陆输入的密码

第四部分

sign_in()
get_content()

完整版代码:

import requests
from bs4 import BeautifulSoup

session = requests.session()

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

def sign_in():#带参数请求登陆
    url_login = 'https://xiaoke.kaikeba.com/example/wordpress/wp-login.php?action=postpass'
    data_login = {'post_password':'xiaoke123',
                  'Submit': '提交'
}    
    res=session.post(url_login, headers=headers, data=data_login)
    print(res.status_code)
    
def get_content():
    #url='https://xiaoke.kaikeba.com/example/wordpress/2019/11/07/互联网圈炸锅啦!有人要帮你加薪啦!/'
    url='https://xiaoke.kaikeba.com/example/wordpress/2019/11/07/%e4%ba%92%e8%81%94%e7%bd%91%e5%9c%88%e7%82%b8%e9%94%85%e5%95%a6%ef%bc%81%e6%9c%89%e4%ba%ba%e8%a6%81%e5%b8%ae%e4%bd%a0%e5%8a%a0%e8%96%aa%e5%95%a6%ef%bc%81/'
    res_article = session.get(url,headers=headers)
    # 获取数据,传入数参数,第一个为url,第二个为请求头
    print(res_article.status_code)
    #判断获取结果是否为空
    bs_article = BeautifulSoup(res_article.text,'html.parser')
    #解析数据
    article= bs_article.find('div',class_='entry-content').text
    # 查找最小父级标签
    print(article)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值