Python獲取接口數(shù)據(jù)的實現(xiàn)示例
首先我們需要下載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 PLT中的image和skimage處理圖片方法詳解
今天小編就為大家分享一篇對python PLT中的image和skimage處理圖片方法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01玩轉(zhuǎn)python爬蟲之URLError異常處理
這篇文章主要介紹了python爬蟲的URLError異常處理,詳細(xì)探尋一下URL\HTTP異常處理的相關(guān)內(nèi)容,通過一些具體的實例來分析一下,非常的簡單,但是卻很實用,感興趣的小伙伴們可以參考一下2016-02-02python通過robert、sobel、Laplace算子實現(xiàn)圖像邊緣提取詳解
這篇文章主要介紹了python通過robert、sobel、Laplace算子實現(xiàn)圖像邊緣提取詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-08-08Python使用functools實現(xiàn)注解同步方法
這篇文章主要介紹了Python使用functools實現(xiàn)注解同步方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2018-02-02