美文网首页大数据 爬虫Python AI Sqlpython爬虫Pythoner集中营
【原创免费】微信公众号文章爬取方法

【原创免费】微信公众号文章爬取方法

作者: _SoLo_ | 来源:发表于2018-06-30 22:06 被阅读27次

    总结一下自己原创的一个爬取微信公众号文章的方法。

    未经同意禁止转载,否则通过维权骑士追究

    【源代码请点击 此处 留言以获取】

    之前在网上也搜索了些爬取微信公众号的资料,大概有如下几种

    Part1 需求分析

    因为之前逛知乎,收藏了不少别人推荐的数据分析、机器学习相关的微信公众号。
    但是在手机上一页页的翻阅浏览,很不方便。所以想了想能否将这些公众号文章下载下来
    这样的话,看起来也方便。但是网上的方法要么太麻烦(对于我这个非爬虫新手来说),要么付费。
    但我的需求其实却很简单——“方便的查找浏览相关公众号的任意文章”

    所以,最后自己造了个轮子(虽然相当低级,但好歹是自己一个一个键盘敲出来的==)

    • 输入:给定公众号ID,和其在传送门站点下的目录页码数
    • 输出Ⅰ:每个公众号对应的文章记录CSV文件
    • 输出Ⅱ: wkhtmltopdf和pdfkit将html转换成PDF文件或者图片文件

    Part2 网上资料

    以下几种方法内容整合自互联网,参考链接
    如有侵权,请联系我删减。

    python爬取

    参考文章

    • 1.需要安装python selenium模块包,通过selenium中的webdriver驱动浏览器获取Cookie的方法、来达到登录的效果;

    • 2.使用webdriver功能需要安装对应浏览器的驱动插件,我这里测试用的是谷歌浏览器:
      google chrome版本为52.0.2743.6 ;
      chromedriver版本为:V2.23
      注意:谷歌浏览器版本和chromedriver需要对应,否则会导致启动时报错。【附:selenium之 chromedriver与chrome版本映射表(更新至v2.30)http://blog.csdn.net/huilan_same/article/details/51896672)】

    • 3.微信公众号登陆地址:https://mp.weixin.qq.com/

    • 4.微信公众号文章接口地址可以在微信公众号后台中新建图文消息,超链接功能中获取:

    • 5.搜索公众号名称

    • 6.获取要爬取的公众号的fakeid

    • 7.选定要爬取的公众号,获取文章接口地址

    • 8.文章列表翻页及内容获取

    AnyProxy代理批量采集

    实现方法:anyproxy+js
    实现方法:anyproxy+java+webmagic

    FiddlerCore

    实现方法:抓包工具,Fiddler4
    通过对多个账号进行抓包分析,可以确定:

    • _biz:这个14位的字符串是每个公众号的“id”,搜狗的微信平台可以获得
    • uin:与访问者有关,微信号id
    • key:和所访问的公众号有关

    步骤:

    1,写按键精灵脚本,在手机上自动点击公号文章列表页,也就是“查看历史消息”;
    2,使用fiddler代理劫持手机端的访问,将网址转发到本地用php写的网页;
    3,在php网页上将接收到的网址备份到数据库;
    4,用python从数据库取出网址,然后进行正常的爬取。

    爬的过程中发现一个问题:
    如果只是想爬取文章内容,似乎并没有访问频率限制,但如果想抓取阅读数、点赞数,超过一定频率后,返回就会变为空值,我设定的时间间隔为10秒,可以正常抓取,这种频率下,一个小时只能抓取360条,已经没什么实际意义了。

    清博 新榜

    如果只是想看数据的话,直接看每天的榜单就可以了,还不用花钱,如果需要接入自己的系统的话,他们也提供api接口

    Part3 项目步骤

    基本原理

    该网站收录了绝大部分的微信公众号文章,会定期更新,经测试发现对爬虫较为友好
    网站页面布局排版规律,不同公众号通过http://chuansong.me/account/almosthuman2014链接中的account区分
    一个公众号合集下的文章翻页也有规律:id号每翻一页+12

    传送门 - 副本.png

    所以思路大概就是

    • 给定公众号ID
    • 获取html
    • 正则表达式提取目标内容
    • 保存爬虫结果(csv)
    • 调用pdfkit和wkhtmltopdf转换网页

    环境

    相关包

    • requests
    • pdfkit

    获取页面

    def get_one_page(url):
        #需要加一个请求头部,不然会被网站封禁
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36'}
        try:       
            response = requests.get(url, headers=headers, timeout=10)
            response.raise_for_status #若不为200,则引发HTTPError错误
            response.encoding = response.apparent_encoding
            return response.text
        except:
            return "产生异常"
    

    注意,目标爬虫网站必须要加headers,否则直接拒绝访问

    正则解析html

    def parse_one_page(html):
        pattern = re.compile('<div class="feed_item_question">.*?<span>.*?<a class="question_link" href="(.*?)".*?_blank">(.*?)</a>.*?"timestamp".*?">(.*?)</span>', re.S)
        items = re.findall(pattern, html)      
        return items
    

    自动跳转页面

    def main(offset, i):    
        url = 'http://chuansong.me/account/' + str(offset) + '?start=' + str(12*i)
        print(url)
        wait = round(random.uniform(1,2),2) # 设置随机爬虫间隔,避免被封
        time.sleep(wait)    
        html = get_one_page(url)    
        for item in parse_one_page(html):
            info = 'http://chuansong.me'+item[0]+','+ item[1]+','+item[2]+'\n'
            info = repr(info.replace('\n', ''))
            print(info)
            #info.strip('\"')  #这种去不掉首尾的“        
            #info = info[1:-1]  #这种去不掉首尾的“ 
            #info.Trim("".ToCharArray())
            #info.TrimStart('\"').TrimEnd('\"')
            write_to_file(info, offset)   
    

    去掉标题中的非法字符

    因为windows下文件命令,有些字符是不能用了,所以需要使用正则剔除

    itle = re.sub('[\\\\/:*?\"<>|]', '', info.loc[indexs]['标题'])
    

    转换html

    使用pandas的read_csv函数读取爬取的csv文件,循环遍历“链接”,“标题”,“日期”

    def html_to_pdf(offset):  
     wait = round(random.uniform(1,2),2) # 设置随机爬虫间隔,避免被封
        time.sleep(wait) 
        path = get_path(offset) 
        path_wk = r'D:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe' #安装wkhtmltopdf的位置
        config = pdfkit.configuration(wkhtmltopdf = path_wk)
        if path == "" :
            print("尚未抓取该公众号")
        else:        
            info = get_url_info(offset)               
            for indexs in info.index:  
                url = info.loc[indexs]['链接']
                title = re.sub('[\\\\/:*?\"<>|]', '', info.loc[indexs]['标题'])
                date = info.loc[indexs]['日期']
                wait = round(random.uniform(4,5),2) # 设置随机爬虫间隔,避免被封
                time.sleep(wait)  
                print(url)
                with eventlet.Timeout(4,False):
                    pdfkit.from_url(url, get_path(offset)+'\\'+ date+'_'+title+'.pdf', configuration=config)   
                    print('转换成功!')
    

    结果展示

    爬取结果

    结果1 - 副本.png

    爬取的几个公众号分文件夹存储


    结果2 - 副本.png

    文件夹目录下的内容


    结果3 - 副本.png

    爬取的CSV内容格式

    生成的PDF结果

    结果4 - 副本.png

    遇到的问题

    问题1

        for item in parse_one_page(html):
            info = 'http://chuansong.me'+item[0]+','+ item[1]+','+item[2]+'\n'
            info = repr(info.replace('\n', ''))
            info = info.strip('\"')
            print(info)
            #info.strip('\"')  #这种去不掉首尾的“        
            #info = info[1:-1]  #这种去不掉首尾的“ 
            #info.Trim("".ToCharArray())
            #info.TrimStart('\"').TrimEnd('\"')
            write_to_file(info, offset) 
    

    解决办法

        字符串中首尾带有“”,使用上文中的#注释部分的各种方法都不好使,
        最后的解决办法是:
        在写入字符串的代码出,加上.strip('\'\"'),以去掉‘和”
        with open(path, 'a', encoding='utf-8') as f:  #追加存储形式,content是字典形式
        f.write(str(json.dumps(content, ensure_ascii=False).strip('\'\"') + '\n'))
        f.close()
    

    问题2

    调用wkhtmltopdf.exe将html转成pdf报错
    调用代码
    
    ``` python
            path_wk = 'D:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'
            config = pdfkit.configuration(wkhtmltopdf = path_wk)
            pdfkit.from_url(url, get_path(offset)+'\\taobao.pdf', configuration=config)
    ``` 
    

    报错信息

            OSError: No wkhtmltopdf executable found: "D:\Program Files\wkhtmltopdin\wkhtmltopdf.exe"
            If this file exists please check that this process can read it. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf    
    

    解决办法

                path_wk = r'D:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'
                config = pdfkit.configuration(wkhtmltopdf = path_wk)
                pdfkit.from_url(url, get_path(offset)+'\\taobao.pdf', configuration=config)
    
            或者
    
                path_wk = 'D:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe'
                config = pdfkit.configuration(wkhtmltopdf = path_wk)
                pdfkit.from_url(url, get_path(offset)+'\\taobao.pdf', configuration=config) 
    

    原因

                Your config path contains an ASCII Backspace, the \b in \bin, 
                which pdfkit appears to be stripping out and converting D:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe
                to D:\Program Files\wkhtmltopdf\wkhtmltopdf.exe.
                
    

    相关文章

      网友评论

      • 提听:打不开
      • _SoLo_:转载或源代码,请点击原文中 第二句话 中的链接
        提听:@_SoLo链接打不开╭(°A°`)╮

      本文标题:【原创免费】微信公众号文章爬取方法

      本文链接:https://www.haomeiwen.com/subject/zuexuftx.html