获取微博热搜爬虫连接MySQL(项目)

前言

之前写过一个爬取热搜的代码,存在本地文件里,现在把数据存在MySQL里。

数据库设计

在这里插入图片描述

代码设计

# -*- encoding: utf-8 -*-
# ---------------------------------------------
# 微博热搜
# ---------------------------------------------
import time
import re
import json
import sys
import copy
import pymysql
from collections import OrderedDict
from parsel import Selector
import requests#引入requests库用于下载网页
from bs4 import BeautifulSoup#BeautifulSoup用于解析网页

url="https://s.weibo.com/top/summary?Refer=top_hot&topnav=1&wvr=6"#所要爬取的网页
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'}#
r=requests.get(url)#请求网站
r.encoding='utf-8'#对页面内容重新编码
data=r.text
soup=BeautifulSoup(data,'html.parser')#使用BeautifulSoup工具
#print(soup.prettify())#显示网站结构
a=[]#创建一个空列表
index=[]
db = pymysql.connect("xxx.xxx.xxx.xxx", "uname", "upass", "表名", use_unicode=1,charset='utf8' )
localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())#获取时间
cursor = db.cursor()
for k in soup.find_all('a',attrs={'href':re.compile('^/weibo?'),'target' : '_blank'}): #把热度标题添加进空列表
    sql = """INSERT INTO 表名(NAME, URL, TIME) VALUES ("%s",'%s','%s')""" % (str(k.get_text().strip()),"https://s.weibo.com"+k.get('href'),localtime)
    print(k.get_text().strip())
    try:
        cursor.execute(sql)
        db.commit()
    except:
        print('数据存在!')
db.close()

在这里插入图片描述

问题解决

1.编码问题

python设置utf8

# -*- encoding: utf-8 -*-

pymysql设置utf8

db = pymysql.connect("xxx.xxx.xxx.xxx", "uname", "upass", "表名", use_unicode=1,charset='utf8' )

navicat设置自动

在这里插入图片描述
PS:选择“自动”,如果选择utf8就会出现乱码

2.主码问题

因为不能存重复的标题,所以要设置主码。如果设置主码,直接存就会报错。解决方法如下:

    try:
        cursor.execute(sql)
        db.commit()
    except:
        print('数据存在!')

后记

现在还需要设置自动运行,可惜我的crawlab还没弄好!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值