ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

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

2022-06-11 12:31:06  阅读:157  来源: 互联网

标签:index python list mo excel cursor urldest mysql import


使用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/

 

标签:index,python,list,mo,excel,cursor,urldest,mysql,import
来源: https://www.cnblogs.com/gangliao81/p/16365628.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有