MySql教程

python中写入excel表格和读写mysql数据库

本文主要是介绍python中写入excel表格和读写mysql数据库,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

使用python爬取网页数据,并写入excel表格和mysql数据库,程序的世界,就是这么爽。

# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import string
import threading
from typing import List

import bs4 as bs4
import pandas as pandas
import pymysql as pymysql
import requests as requests
import xlrd as xlrd
import xlwt as xlwt
list=[]

# 此类为数据类,里面存放电影名称和网络地址
class Iteminfo(object):
    def __init__(self,title,urldest):
        self.title=title
        self.urldest=urldest

# 此函数的作用是把list里的数据写入excel表格中
def writetoexcel():
    # 建一个excel对象
    workbook=xlwt.Workbook()
    # 新建一个名为sheet的表格
    worksheet=workbook.add_sheet("sheet1")
    # 遍历list,取出里面的每一个Iteminfo对象
    for index in range(len(list)):
        worksheet.write(index, 0, label = list[index].title)
        worksheet.write(index, 1, label=list[index].urldest)
    workbook.save('c:\\1.xls')

# 这个函数是为了从网址中提取网页里的所有的播放数据集
def getwebinfo(urlsource):
    #得到网址里的网页的所有内容
    htmltext=requests.get(urlsource).text
    urlroot="https://www.lj1995.cn"
    # 此处为定位标志
    classdetail="mo-paxs-5px mo-pamd-10px mo-cols-info mo-cols-xs4 mo-cols-sm3 mo-cols-lg2"
    # 将网页格式化,以便可以取出里面每个<>里的值及属性
    soup= bs4.BeautifulSoup(htmltext,features="html.parser")
    # 查找到所有的带定位标志的对象
    company_items = soup.find_all("li", class_=classdetail)
    for index in range(len(company_items)):
        # 得到单个的定位对象
        urlitem=company_items[index]
        # 将得到的对象改成字符串
        urlitemtext=str(urlitem)
        # 从字符串里提取到要找的内容的索引
        strstart=urlitemtext.index("href")
        strend=urlitemtext.index(".html")
        # 将需要的信息整合到一起
        urldest=urlroot+urlitemtext[strstart+6:strend+5]
        # 将数据填充到类据类里面
        listitem=Iteminfo(urlitem.contents[3].text,urldest)
        # 调用全局对象list,然后将数据类存到全局对象中
        global list
        list.append(listitem)
        print("名称:" + urlitem.contents[3].text+"  "+urldest)

def getpageinfo(reqtext):
    # 这里从网址中提取页数,如果达到需要的页数,程序就返回上一级,不做任何操作
    page = reqtext[reqtext.index("page/") + 5:reqtext.index(".html")]
    if (int(page) > 3):
        return

    # 这里创建一个分线程去调用其它函数处里业务,速度会快很多
    t1 = threading.Thread(target=getwebinfo, args=(reqtext,))
    t1.start()

    # 这里就是直接调用其它函数,因为需要等待,所以,速度会慢些
    # getwebinfo(reqtext)
    # 此为网页内目标定位
    classroot = "mo-page-item mo-part-vert mo-part-btns mo-bord-muted mo-bord-round" \
                " mo-lhxs-30px mo-lhmd-34px mo-mnxs-0x2 mo-pnxs-5px mo-pnmd-15px" \
                " mo-fsxs-14px mo-back-hover mo-coxs-iblock mo-back-click"
    urlroot = "https://www.lj1995.cn/"
    # 得到网页全部信息
    htmltext = requests.get(reqtext).text
    # 格式化网页信息
    soup = bs4.BeautifulSoup(htmltext, features="html.parser")
    # 从标准的网页信息中提取到有定位的对象集
    company_items = soup.find_all("a", class_=classroot)
    # 遍历这个对象集,并从中到到含有“下一页”字符串的对象,并提示到其中需要的数据,
    # 然后再调用本身再去解析下个网页的内容
    for index in range(len(company_items)):
        strtext=company_items[index].text
        if(strtext=="下一页"):
            urltext=str(company_items[index])
            strstart=urltext.index("data-href")
            strend=urltext.index(".html")
            urldest=urlroot+urltext[strstart+12:strend+5]
            # print(urldest)
            getpageinfo(urldest)

def dosql():
    # 创建一个connect链接对象
    connect=pymysql.connect(host='localhost',db='test',user='root',password='123')
    # 从连接中得到一个游标
    cursor=connect.cursor()
    # 得到当前表格中数据数量
    cursor.execute("select count(*) from webinfo")
    # 得到需要的新的一行的编号
    offrow=cursor.fetchall()[0][0]+1
    # 下面两行是测试插入用的
    # sqltext="insert into webinfo values("+str(count)+",'"+"a"+"','"+"b"+"')"
    # cursor.execute(sqltext)
    # 调用全局对象list并取出里的数据,然后写入数据库,然后提交
    global list
    for index in range(len(list)):
        sqltext="insert into webinfo values("+str(offrow+index)+",'"+list[index].title+"','"+list[index].urldest+"')"
        cursor.execute(sqltext)
    connect.commit()

    # 下面的语名是用来查询数据库里的数据集并打印出来
    # sqltext="select * from bumen"
    # cursor.execute(sqltext)
    # for i in range(cursor.rowcount):
    #     result=cursor.fetchone()
    #     print(result)

    # 数据库边接关闭
    connect.close()

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    getpageinfo("https://www.lj1995.cn/show/13/page/1.html")
    dosql()
    # writetoexcel()
# See PyCharm help at https://www.jetbrains.com/help/pycharm/

 

这篇关于python中写入excel表格和读写mysql数据库的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!