爬取新浪微博发的微博,并保存到数据库(MongoDB)

from urllib.parse import urlencode
import requests
from pyquery import PyQuery as pq
import json
import io  
from pymongo import MongoClient
ccon = MongoClient(host='localhost',port=27017)
db = ccon['weibo']
collection = db['weibo']
base_url = 'https://m.weibo.cn/api/container/getIndex?'
# url_1  = 'https://m.weibo.cn/api/container/getIndex?type=uid&value=2830678474&containerid=1076032830678474'
# url_2  = 'https://m.weibo.cn/api/container/getIndex?type=uid&value=2830678474&containerid=1076032830678474&since_id=4506840937246905'
id_list = []

headers = {
    'Host':'m.weibo.cn',
    'Referer':'https://m.weibo.cn/u/2830678474',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36',
    'X-Requested-With': 'XMLHttpRequest',
}

def get_page(since_id):
    params = {
        'type':'uid',
        'value':'2705604295',
        'containerid':'1076032705604295',
        'since_id':since_id

    }
    url = base_url + urlencode(params)
    try:
        response = requests.get(url,headers=headers)
        if response.status_code == 200:
            return response.json()
    except requests.ConnectionError as e:
        print('Error',e.args)


def parse_page(json1):
    if json1:
        items = json1.get('data').get('cards')
        for item in items:
            item = item.get('mblog')
            weibo ={}
            weibo['id'] = item.get('id')
            weibo['text'] = pq(item.get('text')).text()
            weibo['attitudes'] = item.get('attitudes_count')
            weibo['comments'] = item.get('comments_count')
            weibo['reposts'] = item.get('reposts_count')
            weibo['created_at'] = item.get('created_at')
            yield weibo

def qude_id(num):
    # if since_id = '':
    #     response = requests.get(url_2)
    #     since_id = since_id = (response.json()['data']['cardlistInfo']['since_id']) # 取出第一个since_id
    #     return since_id
    url_2  = 'https://m.weibo.cn/api/container/getIndex?type=uid&value=2830678474&containerid=1076032830678474&since_id=4506840937246905'
    url_3 = 'https://m.weibo.cn/api/container/getIndex?type=uid&value=2705604295&containerid=1076032705604295'
    while 1 < num:
        response = requests.get(url_3)
        since_id = (response.json()['data']['cardlistInfo']['since_id']) # 取出第一个since_id
        # id_list.append(since_id)
        json1 = get_page(since_id)
        returns = parse_page(json1)
        print(type(returns))
        for return1 in returns:
            # print(type(return1))
            # with open('weibo.docx','a+',errors = 'ignore') as f:
            #     # str_json = =json.dumps(return1)
            #     f.write(json.dumps(return1,indent=2,ensure_ascii=False))
            if collection.insert(return1):
                print('Saved to Mongo')
        url_3 = url_3 + '&since_id=' + str(since_id)
        num -= 1

if __name__ == "__main__":
    # for i in range(30):
    # qude_id(30)
    # print(id_list)
    # for id in id_list:
    #     json = get_page(id)
    #     returns = parse_page(json)
    #     for return1 in returns:
    #         print(return1)
    for i in collection.find():
        print(i['text'])
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用Python编程语言来爬取微博热搜,并将数据保存MongoDB数据库中。 具体步骤如下: 1. 安装PythonMongoDB,并安装相应的Python库:pymongo、requests、beautifulsoup4。 2. 使用requests送HTTP请求,获取微博热搜页面的HTML代码。 3. 使用beautifulsoup4库解析HTML代码,提取出热搜榜单的信息。 4. 使用pymongo库连接MongoDB数据库,并将热搜榜单的信息保存数据库中。 需要注意的是,爬取微博热搜需要模拟登录,否则只能获取到部分数据。可以使用selenium库模拟登录,或者使用微博开放平台的API接口来获取数据。 ### 回答2: 爬取微博热搜并保存MongoDB的过程可以分为以下几个步骤: 1. 确定爬虫目标 我们的爬虫目标是微博热搜,因此需要先了解微博热搜的网页结构和信息获取方法。打开微博热搜页面,可以看到列表中包含了许多热门话题,每个话题都有对应的排名、热度和链接地址等信息。这些信息是我们要收集和保存的数据。 2. 分析网页结构和获取数据的方法 接下来需要通过分析热搜页面的HTML代码,确定我们需要获取哪些数据和如何获取这些数据。以Chrome浏览器为例,可以通过右键选择“检查”来打开开者工具,然后在Elements选项卡中查看HTML代码。可以看到每个热搜话题都包含在一个class为'card'的标签中,而该标签下包含了类似下面这样的信息: <div class="card-wrap"> <div class="card-top"> <a href="/weibo?q=%23%E5%A4%A7%E5%98%B4%E9%A3%9E%E8%BD%A6%23&Refer=weibo_card" target="_blank"> <div class="hot"> <span class="line-gradient"></span> <span class="icon-txt">2.6万</span> </div> <div class="title"> <p>#大嘴飞车#</p> </div> </a> </div> <div class="card-content"> <p class="card-txt">#大嘴飞车#剧情重磅!小鹏车队CEO被黑了!你们的神秘大人出现了,眼熟吗?</p> <div class="card-btn"> <a href="/weibo?q=%23%E5%A4%A7%E5%98%B4%E9%A3%9E%E8%BD%A6%23&Refer=weibo_card" target="_blank"> <span class="ico-txt">微博热搜</span> </a> </div> </div> </div> 我们需要获取的数据包括热搜排名、标题、热度、链接地址和相关描述等信息。针对这些信息,可以使用Python的第三方库BeautifulSoup将HTML代码进行解析,并提取我们需要的数据。 3. 编写Python爬虫代码 在分析完网页结构和获取数据方法后,就可以着手编写Python爬虫代码了。首先需要导入所需的第三方库,包括requests、BeautifulSoup和pymongo等,然后通过requests库获取网页HTML源代码: import requests # 热搜页面链接 url = 'https://s.weibo.com/top/summary?cate=realtimehot' # 请求头 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.3'} # 送请求 response = requests.get(url, headers=headers) html = response.text 然后通过BeautifulSoup库解析HTML源代码,提取出热搜话题的相关信息,并构造字典保存到列表中: from bs4 import BeautifulSoup soup = BeautifulSoup(html, 'html.parser') cards = soup.find_all(class_='card') # 爬取到的热搜总数 count = len(cards) # 热搜列表 hot_list = [] # 遍历所有热搜 for card in cards: # 热搜排名 rank = card.find(class_='hot').get_text() # 热搜标题 title = card.find(class_='title').get_text().strip() # 热搜热度 value = card.find(class_='line-gradient').get('style').replace('width:', '').replace('%;', '') # 热搜链接 url = 'https://s.weibo.com' + card.find('a').get('href') # 热搜描述 desc = card.find(class_='card-txt').get_text().strip() # 保存为字典 hot_item = { 'rank': rank, 'title': title, 'value': value, 'url': url, 'desc': desc } hot_list.append(hot_item) 最后,可以使用pymongo库连接MongoDB数据库,将爬取到的热搜数据保存到指定的数据集合中: import pymongo # MongoDB数据库信息 client = pymongo.MongoClient("mongodb://localhost:27017/") db = client["mydb"] col = db["hot_search"] # 向MongoDB数据库插入数据 for hot in hot_list: col.insert_one(hot) 完整的Python代码如下: import requests from bs4 import BeautifulSoup import pymongo # 热搜页面链接 url = 'https://s.weibo.com/top/summary?cate=realtimehot' # 请求头 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.3'} # 送请求 response = requests.get(url, headers=headers) html = response.text soup = BeautifulSoup(html, 'html.parser') cards = soup.find_all(class_='card') # 爬取到的热搜总数 count = len(cards) # 热搜列表 hot_list = [] # 遍历所有热搜 for card in cards: # 热搜排名 rank = card.find(class_='hot').get_text() # 热搜标题 title = card.find(class_='title').get_text().strip() # 热搜热度 value = card.find(class_='line-gradient').get('style').replace('width:', '').replace('%;', '') # 热搜链接 url = 'https://s.weibo.com' + card.find('a').get('href') # 热搜描述 desc = card.find(class_='card-txt').get_text().strip() # 保存为字典 hot_item = { 'rank': rank, 'title': title, 'value': value, 'url': url, 'desc': desc } hot_list.append(hot_item) # MongoDB数据库信息 client = pymongo.MongoClient("mongodb://localhost:27017/") db = client["mydb"] col = db["hot_search"] # 向MongoDB数据库插入数据 for hot in hot_list: col.insert_one(hot) 以上就是爬取微博热搜并保存MongoDB的详细过程。值得注意的是,虽然本例中使用的是BeautifulSoup库进行HTML解析,但在实际情况中,可以根据自己的需要使用其他第三方库,如pyquery等,实现相同的功能。同时,为遵守法律法规和伦理道德,爬虫应避免对网站造成过度负担,如频繁请求、大量下载等,否则有可能触爬虫机制,甚至可能引安全问题和法律责任。 ### 回答3: 微博热搜是指在微博平台上,各种话题或事件在一段时间内获得了大量关注度,被频繁搜索和转的现象。由于微博热搜榜单中的话题和事件极其多样,反应了公众关注的热点和话题,因此对于许多用户和相关企业而言,获取微博热搜信息是非常必要的。 如何爬取微博热搜并存储到mongodb数据库呢?我们可以使用Python编程语言中的一些第三方库来实现这个目标,比如requests、BeautifulSoup、pymongo等。具体步骤如下: 1. 首先,我们需要分析微博热搜榜单的网页结构。使用浏览器打开微博热搜榜单页面,右键点击鼠标,选择“检查”或“审查元素”功能,即可打开浏览器的调试窗口。在调试窗口中,我们可以看到热搜榜单的HTML代码及其CSS样式,我们可以据此编写代码来获取信息。 2. 接着,我们需要使用Python中的requests库向微博热搜榜单页面送GET请求,获取页面的HTML代码。代码示例如下: ``` import requests url = 'https://s.weibo.com/top/summary?cate=realtimehot' 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.3'} response = requests.get(url, headers=headers) html = response.text ``` 3. 接着,我们需要用BeautifulSoup库解析HTML代码,从中提取出微博热搜榜单中的信息。可以按照如下方式提取信息: ``` from bs4 import BeautifulSoup soup = BeautifulSoup(html, 'html.parser') table = soup.find_all('table')[0] trs = table.tbody.find_all('tr') for tr in trs: #提取信息并保存mongodb数据库 ``` 4. 最后,我们需要使用pymongo库将提取出的微博热搜信息保存mongodb数据库中。可以按照如下方式实现: ``` import pymongo client = pymongo.MongoClient('localhost', 27017) db = client['weibo'] collection = db['hot_topic'] for tr in trs: tds = tr.find_all('td') rank = tds[0].text.strip() title = tds[1].text.strip() hot_degree = tds[2].text.strip() creation_time = tds[3].text.strip() search_url = tds[1].a.get('href') data = { 'rank': rank, 'title': title, 'hot_degree': hot_degree, 'creation_time': creation_time, 'search_url': search_url } collection.insert(data) ``` 通过以上步骤,我们就可以爬取微博热搜并保存mongodb数据库中了。这样一来,我们就可以随时随地获取微博热搜的最新情况。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值