最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python獲取接口數(shù)據(jù)的實(shí)現(xiàn)示例

 更新時(shí)間:2023年07月26日 08:34:33   作者:new?code?Boy  
本文主要介紹了Python獲取接口數(shù)據(jù)的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

首先我們需要下載python,我下載的是官方最新的版本 3.8.3

其次我們需要一個(gè)運(yùn)行Python的環(huán)境,我用的是pychram,需要庫(kù)的話我們可以直接在setting里面安裝

代碼:

# -*- codeing = utf-8 -*-
from bs4 import BeautifulSoup  # 網(wǎng)頁(yè)解析,獲取數(shù)據(jù)
import re  # 正則表達(dá)式,進(jìn)行文字匹配`
import urllib.request, urllib.error  # 制定URL,獲取網(wǎng)頁(yè)數(shù)據(jù)
import xlwt  # 進(jìn)行excel操作
#import sqlite3  # 進(jìn)行SQLite數(shù)據(jù)庫(kù)操作
findLink = re.compile(r'<a href="(.*?)">')  # 創(chuàng)建正則表達(dá)式對(duì)象,標(biāo)售規(guī)則   影片詳情鏈接的規(guī)則
findImgSrc = re.compile(r'<img.*src="(.*?)"', re.S)
findTitle = re.compile(r'<span class="title">(.*)</span>')
findRating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')
findJudge = re.compile(r'<span>(\d*)人評(píng)價(jià)</span>')
findInq = re.compile(r'<span class="inq">(.*)</span>')
findBd = re.compile(r'<p class="">(.*?)</p>', re.S)
def main():
    baseurl = "https://movie.douban.com/top250?start="  #要爬取的網(wǎng)頁(yè)鏈接
    # 1.爬取網(wǎng)頁(yè)
    datalist = getData(baseurl)
    savepath = "豆瓣電影Top250.xls"    #當(dāng)前目錄新建XLS,存儲(chǔ)進(jìn)去
    # dbpath = "movie.db"              #當(dāng)前目錄新建數(shù)據(jù)庫(kù),存儲(chǔ)進(jìn)去
    # 3.保存數(shù)據(jù)
    saveData(datalist,savepath)      #2種存儲(chǔ)方式可以只選擇一種
    # saveData2DB(datalist,dbpath)
# 爬取網(wǎng)頁(yè)
def getData(baseurl):
    datalist = []  #用來存儲(chǔ)爬取的網(wǎng)頁(yè)信息
    for i in range(0, 10):  # 調(diào)用獲取頁(yè)面信息的函數(shù),10次
        url = baseurl + str(i * 25)
        html = askURL(url)  # 保存獲取到的網(wǎng)頁(yè)源碼
        # 2.逐一解析數(shù)據(jù)
        soup = BeautifulSoup(html, "html.parser")
        for item in soup.find_all('div', class_="item"):  # 查找符合要求的字符串
            data = []  # 保存一部電影所有信息
            item = str(item)
            link = re.findall(findLink, item)[0]  # 通過正則表達(dá)式查找
            data.append(link)
            imgSrc = re.findall(findImgSrc, item)[0]
            data.append(imgSrc)
            titles = re.findall(findTitle, item)
            if (len(titles) == 2):
                ctitle = titles[0]
                data.append(ctitle)
                otitle = titles[1].replace("/", "")  #消除轉(zhuǎn)義字符
                data.append(otitle)
            else:
                data.append(titles[0])
                data.append(' ')
            rating = re.findall(findRating, item)[0]
            data.append(rating)
            judgeNum = re.findall(findJudge, item)[0]
            data.append(judgeNum)
            inq = re.findall(findInq, item)
            if len(inq) != 0:
                inq = inq[0].replace("。", "")
                data.append(inq)
            else:
                data.append(" ")
            bd = re.findall(findBd, item)[0]
            bd = re.sub('<br(\s+)?/>(\s+)?', "", bd)
            bd = re.sub('/', "", bd)
            data.append(bd.strip())
            datalist.append(data)
    return datalist
# 得到指定一個(gè)URL的網(wǎng)頁(yè)內(nèi)容
def askURL(url):
    head = {  # 模擬瀏覽器頭部信息,向豆瓣服務(wù)器發(fā)送消息
        "User-Agent": "Mozilla / 5.0(Windows NT 10.0; Win64; x64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 80.0.3987.122  Safari / 537.36"
    }
    # 用戶代理,表示告訴豆瓣服務(wù)器,我們是什么類型的機(jī)器、瀏覽器(本質(zhì)上是告訴瀏覽器,我們可以接收什么水平的文件內(nèi)容)
    request = urllib.request.Request(url, headers=head)
    html = ""
    try:
        response = urllib.request.urlopen(request)
        html = response.read().decode("utf-8")
    except urllib.error.URLError as e:
        if hasattr(e, "code"):
            print(e.code)
        if hasattr(e, "reason"):
            print(e.reason)
    return html
# 保存數(shù)據(jù)到表格
def saveData(datalist,savepath):
    print("save.......")
    book = xlwt.Workbook(encoding="utf-8",style_compression=0) #創(chuàng)建workbook對(duì)象
    sheet = book.add_sheet('豆瓣電影Top250', cell_overwrite_ok=True) #創(chuàng)建工作表
    col = ("電影詳情鏈接","圖片鏈接","影片中文名","影片外國(guó)名","評(píng)分","評(píng)價(jià)數(shù)","概況","相關(guān)信息")
    for i in range(0,8):
        sheet.write(0,i,col[i])  #列名
    for i in range(0,250):
        # print("第%d條" %(i+1))       #輸出語句,用來測(cè)試
        data = datalist[i]
        for j in range(0,8):
            sheet.write(i+1,j,data[j])  #數(shù)據(jù)
    book.save(savepath) #保存
# def saveData2DB(datalist,dbpath):
#     init_db(dbpath)
#     conn = sqlite3.connect(dbpath)
#     cur = conn.cursor()
#     for data in datalist:
#             for index in range(len(data)):
#                 if index == 4 or index == 5:
#                     continue
#                 data[index] = '"'+data[index]+'"'
#             sql = '''
#                     insert into movie250(
#                     info_link,pic_link,cname,ename,score,rated,instroduction,info)
#                     values (%s)'''%",".join(data)
#             # print(sql)     #輸出查詢語句,用來測(cè)試
#             cur.execute(sql)
#             conn.commit()
#     cur.close
#     conn.close()
# def init_db(dbpath):
#     sql = '''
#         create table movie250(
#         id integer  primary  key autoincrement,
#         info_link text,
#         pic_link text,
#         cname varchar,
#         ename varchar ,
#         score numeric,
#         rated numeric,
#         instroduction text,
#         info text
#         )
#
#
#     '''  #創(chuàng)建數(shù)據(jù)表
#     conn = sqlite3.connect(dbpath)
#     cursor = conn.cursor()
#     cursor.execute(sql)
#     conn.commit()
#     conn.close()
# 保存數(shù)據(jù)到數(shù)據(jù)庫(kù)
if __name__ == "__main__":  # 當(dāng)程序執(zhí)行時(shí)
    # 調(diào)用函數(shù)
     main()
    # init_db("movietest.db")
     print("爬取完畢!")

-- codeing = utf-8 --,開頭的這個(gè)是設(shè)置編碼為utf-8 ,寫在開頭,防止亂碼。

到此這篇關(guān)于Python獲取接口數(shù)據(jù)的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)Python獲取接口數(shù)據(jù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 超詳細(xì)注釋之OpenCV按位AND OR XOR和NOT

    超詳細(xì)注釋之OpenCV按位AND OR XOR和NOT

    這篇文章主要介紹了OpenCV按位AND OR XOR和NOT運(yùn)算,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-09-09
  • python中HTMLParser模塊知識(shí)點(diǎn)總結(jié)

    python中HTMLParser模塊知識(shí)點(diǎn)總結(jié)

    在本篇文章里小編給大家整理的是一篇關(guān)于python中HTMLParser模塊知識(shí)點(diǎn)內(nèi)容,有興趣的朋友們可以跟著學(xué)習(xí)下。
    2021-01-01
  • pytorch 在sequential中使用view來reshape的例子

    pytorch 在sequential中使用view來reshape的例子

    今天小編就為大家分享一篇pytorch 在sequential中使用view來reshape的例子,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • 快速解釋如何使用pandas的inplace參數(shù)的使用

    快速解釋如何使用pandas的inplace參數(shù)的使用

    這篇文章主要介紹了快速解釋如何使用pandas的inplace參數(shù)的使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07
  • python實(shí)現(xiàn)LRU熱點(diǎn)緩存及原理

    python實(shí)現(xiàn)LRU熱點(diǎn)緩存及原理

    LRU算法根據(jù)數(shù)據(jù)的歷史訪問記錄來進(jìn)行淘汰數(shù)據(jù),其核心思想是“如果數(shù)據(jù)最近被訪問過,那么將來被訪問的幾率也更高”。 。這篇文章主要介紹了python實(shí)現(xiàn)LRU熱點(diǎn)緩存,需要的朋友可以參考下
    2019-10-10
  • python numpy中setdiff1d的用法說明

    python numpy中setdiff1d的用法說明

    這篇文章主要介紹了python numpy中setdiff1d的用法說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2021-04-04
  • Python異常處理、包管理器和正則表達(dá)式實(shí)例代碼

    Python異常處理、包管理器和正則表達(dá)式實(shí)例代碼

    在Python編程中,包管理器、正則表達(dá)式和異常處理是三個(gè)非常重要的概念,這篇文章主要介紹了Python異常處理、包管理器和正則表達(dá)式的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2025-10-10
  • 一文帶你了解Python中的延遲綁定

    一文帶你了解Python中的延遲綁定

    Python中的延遲綁定是指在嵌套函數(shù)中,內(nèi)部函數(shù)在被調(diào)用時(shí)才會(huì)綁定外部函數(shù)的變量,而不是在定義內(nèi)部函數(shù)時(shí)就綁定。本文將通過一些例子帶大家深入了解Python中的延遲綁定,感興趣的可以了解一下
    2023-05-05
  • 使用Python實(shí)現(xiàn)全攝像頭拍照與鍵盤輸入監(jiān)聽功能

    使用Python實(shí)現(xiàn)全攝像頭拍照與鍵盤輸入監(jiān)聽功能

    這篇文章主要介紹了使用Python實(shí)現(xiàn)全攝像頭拍照與鍵盤輸入監(jiān)聽功能,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-08-08
  • win10下python3.5.2和tensorflow安裝環(huán)境搭建教程

    win10下python3.5.2和tensorflow安裝環(huán)境搭建教程

    這篇文章主要為大家詳細(xì)介紹了win10下python3.5.2和tensorflow安裝環(huán)境搭建教程,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-09-09

最新評(píng)論

龙陵县| 根河市| 襄汾县| 隆安县| 利川市| 乌兰浩特市| 仁布县| 防城港市| 香港| 铜山县| 马山县| 承德县| 康马县| 阳高县| 阳城县| 阳城县| 安仁县| 阿克苏市| 镇原县| 永泰县| 遂昌县| 大石桥市| 洛浦县| 紫金县| 昌吉市| 定南县| 洛阳市| 蛟河市| 华坪县| 宣威市| 伊川县| 边坝县| 岑巩县| 时尚| 乐陵市| 沧州市| 屯门区| 淅川县| 红河县| 什邡市| 开鲁县|