selenium爬取微博评论做词云图

导入模块


from lxml import etree
import time
from selenium import webdriver

采用面向对象编程结构

class WeiBo(object):
    driver_path = r'E:\chromedriver.exe'
    csv_name = 'bgsxy_allweibo.csv'

    def __init__(self):

        self.driver = webdriver.Chrome(executable_path=WeiBo.driver_path)
        self.url = 'https://weibo.com/2803301701/ItRmzFAPJ'
        self.comments = []

    def parse_detail_page(self,source):
        html = etree.HTML(source)
        # print(source.content.decode('utf-8'))
        comments = html.xpath("//div[@class='list_box']//div[@class='WB_text']/text()")
        comment_list = []
        for comment in comments:
            comment_list.append(comment)
        print(comment_list)

        # 保存
        print('开始写入txt文件')
        a_str = '\n'.join(comment_list)
        fo = open('1.txt', 'ab+')
        fo.write((a_str).encode('utf-8'))
        fo.close()



    def run(self):
        input('请在chrome中登录weibo.com') # 需要手动登录微博
        self.driver.get(self.url)
        time.sleep(6)
        self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        # 执行点击查看更多
        time.sleep(6)
        for i in range(40):
            time.sleep(5)
            print('第%d次点击'%i)
            self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
            time.sleep(6)
            next_page = self.driver.find_element_by_xpath( "//div[@class='list_box']//span[@class='more_txt']")
            time.sleep(5)
            next_page.click()
            time.sleep(5)
        source = self.driver.page_source
        self.parse_detail_page(source)


        
if __name__ == '__main__':
    spider = WeiBo()
    spider.run()
代码要完善的地方还很多,希望读者提出更多的批评建议
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wency(王斯-CUEB)

我不是要饭的

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值