美文网首页程序员
Python:登录微博获取特定用户时间线内容,简单分析词频

Python:登录微博获取特定用户时间线内容,简单分析词频

作者: 一名普通用户 | 来源:发表于2017-11-23 10:24 被阅读0次

    (大概一两个月前就完成了,没及时更新)

    一直都有想把某个用户的微博内容存档下来的想法,但是人工复制未免效率太低,于是有了这样的一个程序主要是微博的登录比较难模拟,所以打算用selenium直接模拟登录并操作页面。其实用selenium效率并不算太高,但总比人工快。如果有更好的方法欢迎评论。
    之前的程序都是用面向过程写的,这次试试面向对象吧(用面向对象写感觉写的不算太好)

    参考
    GitHub - mozilla/geckodriver: WebDriver <-> Marionette proxy
    Python:argparse、docopt 命令行参数解析模块
    jieba 0.39 : Python Package Index
    Selenium - Web Browser Automation
    Beautiful Soup 4.4.0 文档 — beautifulsoup 4.4.0 文档

    要下载第一个参考内容里 repo 的 release 里的文件放在程序的同级目录才能正常运行!

    实现

    #!/usr/bin/python3
    # -*-coding:utf-8-*-
    
    import requests,os,time,random,argparse
    
    from bs4 import BeautifulSoup
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    
    class Weibo(object):
        def __init__(self,url,type='all'):
            self.url = url
            self.type = type
            # 由于是自己用的小工具,账号密码就直接输入了,或者直接在这里替换
            self.account = input('input your account\n')
            self.password = input('input your password\n')
            # 下载第一个参考里的文件(文件名是geckodriver)放在同级目录里
            self.firefox = webdriver.Firefox(executable_path=os.getcwd()+'/geckodriver')
    
    
        def login(self):
            login_url = 'http://www.weibo.com/login.php'
            self.firefox.get(login_url)
            time.sleep(random.randint(1,5))
            # 输入用户名
            self.firefox.find_element_by_xpath('//*[@id="loginname"]')\
                .send_keys(self.account)
            # 输入密码
            self.firefox.find_element_by_xpath('//*[@id="pl_login_form"]/div/div[3]/div[2]/div/input')\
                .send_keys(self.password)  
            # 点击登陆
            self.firefox.find_element_by_xpath('//*[@id="pl_login_form"]/div/div[3]/div[6]/a')\
                .click()  
            time.sleep(random.randint(1, 5))
            #导出cookie 这段在以后操作种暂时没有用到,暂待以后发掘用法
            cookies = self.firefox.get_cookies() 
            self.session = requests.Session()
            for cookie in cookies:
                self.session.cookies.set(cookie['name'],cookie['value'])
    
    
        def parse(self,html):
            # 解析页面
            soup = BeautifulSoup(html, 'lxml')
            weibos = soup.find_all('div', attrs={'class': 'WB_detail'})
    
            if not weibos:
                return False
    
            for weibo in weibos:
                id = weibo.find('div', attrs={'class': 'WB_from S_txt2'})
                info = weibo.find('div', attrs={'class': 'WB_info'})
                content = weibo.find('div', attrs={'class': 'WB_text W_f14'})
                content_date = weibo.find('a', attrs={'class': 'S_txt2'})
                # print(id.a['href']) 
                print(info.getText().replace(' ', '').replace('\n', '')) 
                # 输出文本
                print(content.getText().replace(' ', '').replace('\n', ''))
                # print(content_date.getText())
                # 多媒体部分,图片视频之类的
                media = weibo.find('div', attrs={'class': 'media_box'})
                # 拓展,例如转发里的内容等
                expand = weibo.find('div',attrs={'class':'WB_expand S_bg1'})
    
                # 此处由于没有用到暂时没有实现,日后再更新
                if media:
                    pics = media.find_all('img')
                    for pic in pics:
                        pass
    
                if expand:
                    pass
    
            return True
    
    
        def download(self):
            page = 1
    
            # 筛选原创微博
            if self.type == 'origin':
                traverse_url = self.url + '?from=myfollow_all&profile_ftype=1&is_ori=1'
            # 全部微博
            elif self.type == 'all':
                traverse_url = self.url + '?from=myfollow_all&is_all=1'
            else:
                print('unsupported type: '+self.type)
    
            self.firefox.get(traverse_url+'&page='+str(page))
            # 拉到页面底部
            self.__to_end__()
            # 存在该页面
            while(self.parse(self.firefox.page_source)):
                time.sleep(5)
                page = page + 1
                self.firefox.get(traverse_url+'&page='+str(page))
                self.__to_end__()
    
            self.firefox.close()
    
        def __to_end__(self):
            # 按三次 END 键实现拉到页面底部功能
            self.firefox.find_element_by_xpath('/html/body').send_keys(Keys.END)
            time.sleep(1)
            self.firefox.find_element_by_xpath('/html/body').send_keys(Keys.END)
            time.sleep(1)
            self.firefox.find_element_by_xpath('/html/body').send_keys(Keys.END)
            time.sleep(1)
    
    if __name__ == '__main__':
        parser = argparse.ArgumentParser() # 不懂请看参考中的第二个链接
        parser.add_argument('--url',help='weibo URL,make sure you input a vaild URL')
        parser.add_argument('--type',help='\'origin\' or \'all\',all for default')
    
        args = parser.parse_args()
    
        wb = Weibo(args.url)
        wb.login()
        time.sleep(5)
        wb.download()
    

    分析词频是个很复杂的工作,所以这里只是单纯的用jieba将句子分成词,排个序而已。网上也有相应 API ,效果各异。

    #/usr/bin/python3
    # -*- coding:utf-8 -*-
    
    import jieba,re
    
    def vaild(word): #判断有效性
        p1 = re.compile(u'[\u4E00-\u9FA5]{1,}') # 中文
        p2 = re.compile(u'[a-zA-z]{1,}') # 英文
        if p1.match(word) or p2.match(word):
            return True
        return False
    
    if __name__ == '__main__':
    
        dmap = {}
        with open(‘jieba-word.txt','r') as file: # 将上面的输出保存到这个文件夹里
            for line in file:
                res = jieba.cut(line,cut_all=False)
                rres = '#'.join(res)
                l = rres.split('#')
    
                for val in l:
                    if vaild(val):
                        if val in dmap:
                            dmap[val] += 1
                        else:
                            dmap[val] = 1
    
        dlist = [(val,dmap[val]) for val in dmap] # 为后续排序转换
        dlist = sorted(dlist,key=lambda tup:(tup[1], tup[0]),reverse=True) # 降序排序
        
        for word in dlist:
            if word[1] > 3: # 出现三次以上才输出
                print(word)
    

    写得不够好,再接再厉!

    来自个人 Python 文集

    相关文章

      网友评论

        本文标题:Python:登录微博获取特定用户时间线内容,简单分析词频

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