亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

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

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

代碼:

# -*- codeing = utf-8 -*-
from bs4 import BeautifulSoup  # 網(wǎng)頁解析,獲取數(shù)據(jù)
import re  # 正則表達(dá)式,進(jìn)行文字匹配`
import urllib.request, urllib.error  # 制定URL,獲取網(wǎng)頁數(shù)據(jù)
import xlwt  # 進(jìn)行excel操作
#import sqlite3  # 進(jìn)行SQLite數(shù)據(jù)庫操作
findLink = re.compile(r'<a href="(.*?)">')  # 創(chuàng)建正則表達(dá)式對象,標(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*)人評價</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)頁鏈接
    # 1.爬取網(wǎng)頁
    datalist = getData(baseurl)
    savepath = "豆瓣電影Top250.xls"    #當(dāng)前目錄新建XLS,存儲進(jìn)去
    # dbpath = "movie.db"              #當(dāng)前目錄新建數(shù)據(jù)庫,存儲進(jìn)去
    # 3.保存數(shù)據(jù)
    saveData(datalist,savepath)      #2種存儲方式可以只選擇一種
    # saveData2DB(datalist,dbpath)
# 爬取網(wǎng)頁
def getData(baseurl):
    datalist = []  #用來存儲爬取的網(wǎng)頁信息
    for i in range(0, 10):  # 調(diào)用獲取頁面信息的函數(shù),10次
        url = baseurl + str(i * 25)
        html = askURL(url)  # 保存獲取到的網(wǎng)頁源碼
        # 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
# 得到指定一個URL的網(wǎng)頁內(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對象
    sheet = book.add_sheet('豆瓣電影Top250', cell_overwrite_ok=True) #創(chuàng)建工作表
    col = ("電影詳情鏈接","圖片鏈接","影片中文名","影片外國名","評分","評價數(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))       #輸出語句,用來測試
        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)     #輸出查詢語句,用來測試
#             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ù)庫
if __name__ == "__main__":  # 當(dāng)程序執(zhí)行時
    # 調(diào)用函數(shù)
     main()
    # init_db("movietest.db")
     print("爬取完畢!")

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

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

相關(guān)文章

  • 一百行python代碼將圖片轉(zhuǎn)成字符畫

    一百行python代碼將圖片轉(zhuǎn)成字符畫

    這篇文章主要為大家詳細(xì)介紹了一百行python代碼將圖片轉(zhuǎn)成字符畫 ,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-11-11
  • 對python PLT中的image和skimage處理圖片方法詳解

    對python PLT中的image和skimage處理圖片方法詳解

    今天小編就為大家分享一篇對python PLT中的image和skimage處理圖片方法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-01-01
  • Python如何根據(jù)字典中的值排序

    Python如何根據(jù)字典中的值排序

    這篇文章主要介紹了Python如何根據(jù)字典中的值排序問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • 在Pandas中更改DataFrame中的值

    在Pandas中更改DataFrame中的值

    這篇文章主要介紹了在Pandas中更改DataFrame中的值方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • Python如何獲取免費(fèi)高匿代理IP及驗證

    Python如何獲取免費(fèi)高匿代理IP及驗證

    這篇文章主要介紹了Python如何獲取免費(fèi)高匿代理IP及驗證問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-06-06
  • 利用python批量檢查網(wǎng)站的可用性

    利用python批量檢查網(wǎng)站的可用性

    當(dāng)大家的站點(diǎn)越來越來越多的時候會發(fā)現(xiàn)管理起來也挺復(fù)雜的,所以這篇文章給大家分享下利用python批量檢查網(wǎng)站的可用性的功能,對大家管理網(wǎng)站具有很實用的價值,有需要的朋友可以參考借鑒。
    2016-09-09
  • 玩轉(zhuǎn)python爬蟲之URLError異常處理

    玩轉(zhuǎn)python爬蟲之URLError異常處理

    這篇文章主要介紹了python爬蟲的URLError異常處理,詳細(xì)探尋一下URL\HTTP異常處理的相關(guān)內(nèi)容,通過一些具體的實例來分析一下,非常的簡單,但是卻很實用,感興趣的小伙伴們可以參考一下
    2016-02-02
  • Restful_framework視圖組件代碼實例解析

    Restful_framework視圖組件代碼實例解析

    這篇文章主要介紹了Restful_framework視圖組件代碼實例解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-11-11
  • python通過robert、sobel、Laplace算子實現(xiàn)圖像邊緣提取詳解

    python通過robert、sobel、Laplace算子實現(xiàn)圖像邊緣提取詳解

    這篇文章主要介紹了python通過robert、sobel、Laplace算子實現(xiàn)圖像邊緣提取詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-08-08
  • Python使用functools實現(xiàn)注解同步方法

    Python使用functools實現(xiàn)注解同步方法

    這篇文章主要介紹了Python使用functools實現(xiàn)注解同步方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
    2018-02-02

最新評論