python爬取微博话题下面的帖子并存入excel文件

此次写的是python爬取微博话题下面的帖子,示例代码以爬取#转发这个杨超越#

https://s.weibo.com/weibo/%23%E8%BD%AC%E5%8F%91%E8%BF%99%E4%B8%AA%E6%9D%A8%E8%B6%85%E8%B6%8A%23

# -*- coding:utf-8 -*-
__author__ = 'TengYu'
import requests
import json
import re
import time
import xlwt
from bs4 import  BeautifulSoup



headers = {
    'User-agent' : 'Your-Agent',
    'Cookie':'Your-cookie'
}


url = 'https://m.weibo.cn/api/container/getIndex?containerid=231522type%3D1%26q%3D%23%E8%BD%AC%E5%8F%91%E8%BF%99%E4%B8%AA%E6%9D%A8%E8%B6%85%E8%B6%8A%23&page_type=searchall&page='




class Tool:
    deleteImg = re.compile('<img.*?>')
    newLine =re.compile('<tr>|<div>|</tr>|</div>')
    deleteAite = re.compile('//.*?:')
    deleteAddr = re.compile('<a.*?>.*?</a>')
    deleteTag = re.compile('<.*?>')

    @classmethod
    def replace(cls,x):
        x = re.sub(cls.deleteImg,'',x)
        x = re.sub(cls.deleteAite,'',x)
        x = re.sub(cls.deleteAddr, '', x)
        x = re.sub(cls.newLine,'',x)
        x = re.sub(cls.deleteTag,'',x)
        return x.strip()


class tiezi(object):
    def get_info(self,url):
        File = open('filename.txt', 'w')
        excel = xlwt.Workbook(encoding='utf-8')
        sheet = excel.add_sheet('sheet1')
        sheet.write(0, 0, 'id')
        sheet.write(0, 1, 'name')
        sheet.write(0, 2, 'time')
        sheet.write(0, 3, 'text')
        count = 0
        for i in range(1,41):
            url = 'https://m.weibo.cn/api/container/getIndex?containerid=231522type%3D1%26q%3D%23%E8%BD%AC%E5%8F%91%E8%BF%99%E4%B8%AA%E6%9D%A8%E8%B6%85%E8%B6%8A%23&page_type=searchall&page=' + str(i)
            response = requests.get(url)
            print url
            resj = json.loads(response.text)
            data = resj.get('data').get('cards')
            for i in range(0,len(data)):
                datatemp = data[i]
                card_group = datatemp.get('card_group')
                for j in range(0,len(card_group)):
                    temp = card_group[j]
                    card_type = temp.get('card_type')
                    if (int)(card_type) == 9:
                        count += 1
                        mblog = temp.get('mblog')
                        text = mblog.get('text')
                        user = mblog.get('user')
                        id = user.get('id')
                        screen_name = user.get('screen_name')
                        created_at = mblog.get('created_at')
                        text=Tool.replace(text)
                        File.write(str(text.encode('utf-8')) + '\n')
                        sheet.write(count,0,str(id.encode('utf-8')))
                        sheet.write(count,1,screen_name.encode('utf-8'))
                        sheet.write(count,2,created_at.encode('utf-8'))
                        sheet.write(count,3,text.encode('utf-8'))
            print ("已经获取" + str(count)+"条数据")
            time.sleep(2)
            excel.save('filename.xls')




if __name__=='__main__':
    Tiezi = tiezi()
    Tiezi.get_info(url)

 

为例,基本的url分析没太多难题,大家多写写就熟练了,毕竟不是什么技术活,我直接贴代码了

尊重原作,转载请注明,转载自:https://blog.csdn.net/kr2563

 

  • 8
    点赞
  • 56
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
爬取微博话题,可以使用Python中的requests和BeautifulSoup库来实现。具体步骤如下: 1. 打开微博网页版,搜索想要爬取话题,并复制该话题的url。 2. 使用requests库发送GET请求获取该话题的html源代码。 ```python import requests url = 'https://weibo.cn/search/mblog?hideSearchFrame=&keyword=%23Python%E5%BC%80%E5%8F%91%23' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299' } response = requests.get(url, headers=headers) html = response.content ``` 3. 使用BeautifulSoup库解析html源代码,并获取该话题的所有微博信息。 ```python from bs4 import BeautifulSoup soup = BeautifulSoup(html, 'lxml') weibo_list = soup.find_all('div', class_='c') ``` 4. 遍历微博列表,获取每条微博的内容、发布时间、点赞数、评论数、转发数等信息。 ```python for weibo in weibo_list: # 获取微博内容 content = weibo.find('span', class_='ctt').get_text() # 获取发布时间 time = weibo.find('span', class_='ct').get_text().split('\xa0')[0] # 获取点赞数、评论数、转发数 stats = weibo.find_all('a') up_num = stats[0].text.split('[')[1].split(']')[0] repost_num = stats[1].text.split('[')[1].split(']')[0] comment_num = stats[2].text.split('[')[1].split(']')[0] # 输出微博信息 print('微博内容:', content) print('发布时间:', time) print('点赞数:', up_num) print('转发数:', repost_num) print('评论数:', comment_num) ``` 以上就是使用Python爬取微博话题的基本步骤和代码示例。需要注意的是,爬取微博数据需要遵守相关法律法规和网站协议,不得用于商业用途。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值