zoukankan      html  css  js  c++  java
  • 第14.16节 爬虫实战2:赠人玫瑰,手留余香! request+BeautifulSoup实现csdn博文自动点赞

    写在前面:本文仅供参考学习,请勿用作它途,禁止转载!

    在《第14.14节 爬虫实战准备:csdn博文点赞过程http请求和响应信息分析》老猿分析了csdn博文点赞处理的http请求和响应报文,在《第14.15节 爬虫实战1:使用Python和selenium实现csdn博文点赞》中通过selenium方式实现了博文自动点赞,但selenium方式老猿觉得并不是一个真正的爬虫实现方式,因此本节老猿将通过request+BeautifulSoup的方式实现一个真正爬虫式的CSDN博文自动点赞。

    二、 csdn点赞实现的基本思路
    本节将实现读取文本文件c: empurllist.txt中的需要点赞的csdn博文记录(一行一个url地址),对每一行记录逐一进行如下处理:
    1、 利用已经登录会话读取博文并利用beatifulsoap解析判断博文是否已经点赞,如果是则处理下一条url。本步骤需要知道:
    1)怎么利用已经登录会话构建http请求头(函数mkhead)模拟已登录会话的浏览器访问,具体知识请参考《第14.5节 利用浏览器获取的http信息构造Python网页访问的http请求头》;
    2)怎么使用beatifulsoap解析报文,本次老猿构建beatifulsoap对象soup后,使用“标签+属性+属性值”的css 选择器来定位点赞按钮,代码为“soup.select(“button[title=‘点赞’]”)”,相关方法请参考《第14.12节 Python中使用BeautifulSoup解析http报文:使用select方法快速定位内容》。
    2、 根据博文地址计算出点赞http请求的url,对应函数为getthumbsupURL;
    3、 发送点赞的url请求并读取返回的响应报文;
    4、 对响应报文解码后判断是否点赞成功,具体判断方法请参考《第14.14节 爬虫实战准备:csdn博文点赞过程http请求和响应信息分析》。代码中判断点赞成功没有使用beatifulsoap,直接使用字符串查找方法,因为该响应报文非常简单,使用字符串查找非常方便。

    三、 完整点赞代码
    注意:http请求的cookie参数老猿在下面代码中采用了只取一部分真实数据处理以保护老猿自己的会话信息安全,各位需要按照《第14.5节 利用浏览器获取的http信息构造Python网页访问的http请求头》介绍的方法将自己的信息填入请求头中。

    #coding:utf-8         
    #使用request和beatifulosap实现csdn博文点赞
    import time 
    import fileinput
    from bs4 import BeautifulSoup
    import urllib.request
    
    def mkhead():
        #根据使用人员登录csdn的http会话信息填写   
        header = {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
        'Accept-Language':'zh-CN,zh;q=0.9',
        'Connection':'keep-alive',
        'Cookie':'uuid_tt_dd=10_35489889920-1563497330616-876822; UserName=LaoYuanPython;......',
        'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'}
            
        return header 
        
    def getthumbsupURL(articleURL):
        """
        根据点赞文章的url地址计算出点赞请求的url,二者url案例如下:
        需要点赞文章:https://blog.csdn.net/LaoYuanPython/article/details/100585881
        点赞请求:https://blog.csdn.net/laoyuanpython/phoenix/article/digg?ArticleId=100585881
        """
        
        urlwords = articleURL.split('/')
        articleid = urlwords[6] 
        digurlwords = urlwords[0:4]
        digurlwords.append('phoenix/article/digg?ArticleId='+articleid)
        digurl = ''
        for words in digurlwords:
            digurl = digurl+words+'/'
        return digurl
    
    def isthumbsup(url,header):
        """
        读取指定url的博文判断是否已经点赞
        返回值:
        True:已经点赞或读取报文失败
        False:未点赞
        """
        
        req = urllib.request.Request(url=url,headers=header)
        try: text = urllib.request.urlopen(req).read().decode()  
        except Exception: 
            print(f"读取 {url} 内容解码判断是否点赞失败,失败原因:
    {e}")   
        soup = BeautifulSoup(text, 'lxml')
       
        button1 = soup.select("button[title='点赞']")
        button2 = soup.select("button[title='取消点赞']")
        if button1: return False
        elif button2:return True
       
        
    def thumbsup(url):
        """
        对指定url的cdn博文点赞
        url:需要点赞文章的url 
        """
        
        #判断该博文是否已经点赞过
        header = mkhead()
        thumbsuped = isthumbsup(url,header)
        if thumbsuped: 
            print(f"{url} 已点赞!")
            return 2
        thumbsupUrl = getthumbsupURL(url)    
        req = urllib.request.Request(url=thumbsupUrl,headers=header)
        text = urllib.request.urlopen(req).read().decode()
    
        if  text.find('"status":true')>=0:
            print(f"{url} 点赞成功!")
            return 1
        else:
            print(f"{url} 点赞失败!")
            return 0
            
            
    def batchthumbsup(filename):
        count = 0
        for line in fileinput.input(filename):
            urlline = line.strip(' 
    ')
            thumbsup(urlline) 
            count+=1
            if count>=5:break       
            time.sleep(1)     
     
    batchthumbsup(r'c:	empurllist.txt')
    
    
    

    大家将上述代码拷贝存入一个py文件中,并将其中的cookie替换为自己登陆的cookie信息,就可以以自己的账户给他人博文点赞了。不过注意,为了保持代码简洁,老猿都没有加异常处理,真正实现时最好加上。

    老猿Python,跟老猿学Python!
    博客地址:https://blog.csdn.net/LaoYuanPython

    老猿Python博客文章目录:https://blog.csdn.net/LaoYuanPython/article/details/98245036
    请大家多多支持,点赞、评论和加关注!谢谢!

  • 相关阅读:
    cell list of blocks physical read等待事件
    cell manager discovering disks等待事件
    OOP
    静态网页与动态网页的区别
    一个HTTP请求的详细过程
    PING 确认网络连接情况
    软件开发模型
    搭建网站的全套流程
    Design Diagram
    网络基础
  • 原文地址:https://www.cnblogs.com/LaoYuanPython/p/11931752.html
Copyright © 2011-2022 走看看