pycharm、微博爬取个人数据存入Mongodb

前提安装好RoBo 3T可视化工具,安装好pymongo库。

下面是爬取微博个人数据,有微博id,正文,点赞数,评论数,转发数

from urllib.parse import urlencode
import requests
from pyquery import PyQuery as pq
from pymongo import MongoClient

#表示请求的URL的前半部分
base_url = 'https://m.weibo.cn/api/container/getIndex?'

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/77.0.3865.75 Safari/537.36',
    'X-Requested-With': 'XMLHttpRequest'
}

#我们通过PyMongo库里的MongoClient,第一个参数host是mongobd的地址,第二个参数是端口port(默认27017)
client = MongoClient(host='127.0.0.1', port=27017)
#选择数据库
db = client['weibo']
#选择好数据库后我们需要指定要操作的集合,与数据库的选择类似
collection = db['weibo']
max_page = 10

def get_page(page):
    #构造参数字典,其中type、value、containerid是固定参数,page是可变参数
    params = {
        'type': 'uid',
        'value': '2830678474',
        'containerid': '1076032830678474',
        'page': page
    }
    #调用urlopen()方法将参数转化为URL的GET请求参数,base_url与参数拼合形成一个新的URL
    url = base_url + urlencode(params)
    try:
        #requests请求这个链接,加入headers参数
        response = requests.get(url, headers=headers)
        #判断响应的状态码,如果是200,则直接调用json()方法将内容解析为JSON返回,否则不返回任何信息
        if response.status_code == 200:
            return response.json(), page
    #如果出现异常,则捕获并输出其异常信息
    except requests.ConnectionError as e:
        print('Error', e.args)

#定义一个解析方法,用来从结果中提取想要的信息
def parse_page(json, page:int):
    if json:
        #可以先遍历cards
        items = json.get('data').get('cards')
        for index, item in enumerate(items):
            if page == 1 and index == 1:
                continue
            else:
                #然后获取mblog中的各个信息,赋值为一个新的字典返回即可
                item = item.get('mblog', {})
                weibo = {}
                weibo['id'] = item.get('id')                    #微博的ID
                weibo['text'] = pq(item.get('text')).text()     #正文
                weibo['attitudes'] = item.get('attitudes_Count') #点赞数
                weibo['comments'] = item.get('comments_Count')  #评论数
                weibo['reports'] = item.get('reports_Count')    #转发数
                yield weibo

def save_to_mongo(result):
    if collection.insert(result):
        print('Save to Mongo')

if __name__ == '__main__':
    for page in range(1, max_page + 1):
        json = get_page(page)
        results = parse_page(*json)
        for result in results:
            print(result)
            save_to_mongo(result)

可视化工具可以看到下载的数据:

 

 

  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
以下是一个简单的 Python 代码示例,演示如何使用 PyCharm 爬取网上数据并将其存储到 MySQL 数据: 首先,需要安装 `requests` 和 `beautifulsoup4` 这两个库,以便从网页上获取数据并进行解析: ``` pip install requests pip install beautifulsoup4 ``` 然后,需要安装 MySQL Connector 驱动程序: ``` pip install mysql-connector-python ``` 接下来,可以使用以下代码从网页上获取数据并将其存储到 MySQL 数据: ```python import requests from bs4 import BeautifulSoup import mysql.connector # 连接 MySQL 数据库 mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="mydatabase" ) # 获取网页内容 url = 'https://example.com' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # 解析数据 data = [] for item in soup.find_all('div', class_='item'): title = item.find('h2').text.strip() description = item.find('p').text.strip() data.append((title, description)) # 将数据存储到 MySQL 数据 mycursor = mydb.cursor() sql = "INSERT INTO items (title, description) VALUES (%s, %s)" mycursor.executemany(sql, data) mydb.commit() ``` 在以上代码,需要将 `yourusername`、`yourpassword` 和 `mydatabase` 替换为您自己的 MySQL 数据库的用户名、密码和数据库名称。同时,需要将 `https://example.com` 替换为您要爬取数据的网址,并根据需要修改解析数据的代码。 以上代码只是一个简单示例,实际情况可能会更加复杂。如果您在使用 PyCharm 进行爬虫开发时遇到问题,可以查看 PyCharm 的文档和官方论坛,寻求帮助。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值