前言
之前写过一个爬取热搜的代码,存在本地文件里,现在把数据存在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还没弄好!