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

Python爬取豆瓣數(shù)據(jù)實(shí)現(xiàn)過程解析

 更新時間:2020年10月27日 11:13:25   作者:阿西莫多  
這篇文章主要介紹了Python爬取豆瓣數(shù)據(jù)實(shí)現(xiàn)過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下

代碼如下

from bs4 import BeautifulSoup #網(wǎng)頁解析,獲取數(shù)據(jù)
import sys #正則表達(dá)式,進(jìn)行文字匹配
import re
import urllib.request,urllib.error #指定url,獲取網(wǎng)頁數(shù)據(jù)
import xlwt #使用表格
import sqlite3
import lxml

以上是引用的庫,引用庫的方法很簡單,直接上圖:

上面第一步算有了,下面分模塊來,步驟算第二步來:

這個放在開頭

def main():
  baseurl ="https://movie.douban.com/top250?start="
  datalist = getData(baseurl)
  savepath=('douban.xls')
  saveData(datalist,savepath)

這個放在末尾

if __name__ == '__main__':
main()

不難看出這是主函數(shù),里面的話是對子函數(shù)的調(diào)用,下面是第三個步驟:子函數(shù)的代碼

對網(wǎng)頁正則表達(dá)提取(放在主函數(shù)的后面就可以)

findLink = re.compile(r'<a href="(.*?)" rel="external nofollow" rel="external nofollow" >') #創(chuàng)建正則表達(dá)式對象,表示規(guī)則(字符串的模式)
#影片圖片
findImg = re.compile(r'<img.*src="(.*?)" width="100"/>',re.S)#re.S取消換行符
#影片片面
findtitle= re.compile(r'<span class="title">(.*?)</span>')
#影片評分
fileRating = re.compile(r'<span class="rating_num" property="v:average">(.*?)</span>')
#找到評價的人數(shù)
findJudge = re.compile(r'<span>(\d*)人評價</span>')
#找到概識
findInq =re.compile(r'<span class="inq">(.*?)</span>')
#找到影片的相關(guān)內(nèi)容
findBd = re.compile(r'<p class="">(.*?)</p>',re.S)

爬數(shù)據(jù)核心函數(shù)

def getData(baseurl):
  datalist=[]
  for i in range(0,10):#調(diào)用獲取頁面的函數(shù)10次
    url = baseurl + str(i*25)
    html = askURl(url)
  #逐一解析
    soup = BeautifulSoup(html,"html.parser")
    for item in soup.find_all('div',class_="item"):
    #print(item)
      data=[]
      item = str(item)
 
      link = re.findall(findLink,item)[0] #re庫用來通過正則表達(dá)式查找指定的字符串
      data.append(link)
      titles =re.findall(findtitle,item)
      if(len(titles)==2):
        ctitle=titles[0].replace('\xa0',"")
        data.append(ctitle)#添加中文名
        otitle = titles[1].replace("\xa0/\xa0Perfume:","")
        data.append(otitle)#添加外國名
      else:
        data.append(titles[0])
        data.append(' ')#外國名字留空
 
      imgSrc = re.findall(findImg,item)[0]
      data.append(imgSrc)
 
      rating=re.findall(fileRating,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) #去掉<br/>
      bd =re.sub('\xa0'," ",bd)
      data.append(bd.strip()) #去掉前后的空格
 
      datalist.append(data) #把處理好的一部電影信息放入datalist
 
  return datalist

獲取指定網(wǎng)頁內(nèi)容

def askURl(url):
 
  head = {
    "User-Agent": "Mozilla / 5.0(Windows NT 10.0;WOW64) Apple"
    +"WebKit / 537.36(KHTML, likeGecko) Chrome / 78.0.3904.108 Safari / 537.36"
  }
#告訴豆瓣我們是瀏覽器我們可以接受什么水平的內(nèi)容
  request = urllib.request.Request(url,headers=head)
  html=""
  try:
    response = urllib.request.urlopen(request)
    html = response.read().decode("utf-8")
    # print(html)
  except urllib.error.URLError as e:
    if hasattr(e,"code"):
      print(e.code)
    if hasattr(e,"reason"):
      print(e.reason)
  return html

將爬下來的數(shù)據(jù)保存到表格中

ef saveData(datalist,savepath):
  print("保存中。。。")
  book = xlwt.Workbook(encoding="utf-8",style_compression=0) # 創(chuàng)建workbook對象
  sheet = book.add_sheet('douban',cell_overwrite_ok=True) #創(chuàng)建工作表 cell_overwrite_ok表示直接覆蓋
  col = ("電影詳情鏈接","影片中文網(wǎng)","影片外國名","圖片鏈接","評分","評價數(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])
 
  book.save(savepath)

以上就是整個爬數(shù)據(jù)的整個程序,這僅僅是一個非常簡單的爬取,如果想要爬更難的網(wǎng)頁需要實(shí)時分析

整個程序代碼

from bs4 import BeautifulSoup #網(wǎng)頁解析,獲取數(shù)據(jù)
import sys #正則表達(dá)式,進(jìn)行文字匹配
import re
import urllib.request,urllib.error #指定url,獲取網(wǎng)頁數(shù)據(jù)
import xlwt #使用表格
import sqlite3
import lxml
 
def main():
  baseurl ="https://movie.douban.com/top250?start="
  datalist = getData(baseurl)
  savepath=('douban.xls')
  saveData(datalist,savepath)
#影片播放鏈接
findLink = re.compile(r'<a href="(.*?)" rel="external nofollow" rel="external nofollow" >') #創(chuàng)建正則表達(dá)式對象,表示規(guī)則(字符串的模式)
#影片圖片
findImg = re.compile(r'<img.*src="(.*?)" width="100"/>',re.S)#re.S取消換行符
#影片片面
findtitle= re.compile(r'<span class="title">(.*?)</span>')
#影片評分
fileRating = re.compile(r'<span class="rating_num" property="v:average">(.*?)</span>')
#找到評價的人數(shù)
findJudge = re.compile(r'<span>(\d*)人評價</span>')
#找到概識
findInq =re.compile(r'<span class="inq">(.*?)</span>')
#找到影片的相關(guān)內(nèi)容
findBd = re.compile(r'<p class="">(.*?)</p>',re.S)
 
def getData(baseurl):
  datalist=[]
  for i in range(0,10):#調(diào)用獲取頁面的函數(shù)10次
    url = baseurl + str(i*25)
    html = askURl(url)
  #逐一解析
    soup = BeautifulSoup(html,"html.parser")
    for item in soup.find_all('div',class_="item"):
    #print(item)
      data=[]
      item = str(item)
 
      link = re.findall(findLink,item)[0] #re庫用來通過正則表達(dá)式查找指定的字符串
      data.append(link)
      titles =re.findall(findtitle,item)
      if(len(titles)==2):
        ctitle=titles[0].replace('\xa0',"")
        data.append(ctitle)#添加中文名
        otitle = titles[1].replace("\xa0/\xa0Perfume:","")
        data.append(otitle)#添加外國名
      else:
        data.append(titles[0])
        data.append(' ')#外國名字留空
 
      imgSrc = re.findall(findImg,item)[0]
      data.append(imgSrc)
 
      rating=re.findall(fileRating,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) #去掉<br/>
      bd =re.sub('\xa0'," ",bd)
      data.append(bd.strip()) #去掉前后的空格
 
      datalist.append(data) #把處理好的一部電影信息放入datalist
 
  return datalist
 
#得到指定一個url的網(wǎng)頁內(nèi)容
def askURl(url):
 
  head = {
    "User-Agent": "Mozilla / 5.0(Windows NT 10.0;WOW64) Apple"
    +"WebKit / 537.36(KHTML, likeGecko) Chrome / 78.0.3904.108 Safari / 537.36"
  }
#告訴豆瓣我們是瀏覽器我們可以接受什么水平的內(nèi)容
  request = urllib.request.Request(url,headers=head)
  html=""
  try:
    response = urllib.request.urlopen(request)
    html = response.read().decode("utf-8")
    # print(html)
  except urllib.error.URLError as e:
    if hasattr(e,"code"):
      print(e.code)
    if hasattr(e,"reason"):
      print(e.reason)
  return html
 
def saveData(datalist,savepath):
  print("保存中。。。")
  book = xlwt.Workbook(encoding="utf-8",style_compression=0) # 創(chuàng)建workbook對象
  sheet = book.add_sheet('douban',cell_overwrite_ok=True) #創(chuàng)建工作表 cell_overwrite_ok表示直接覆蓋
  col = ("電影詳情鏈接","影片中文網(wǎng)","影片外國名","圖片鏈接","評分","評價數(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])
 
  book.save(savepath)
 
if __name__ == '__main__':
  main()

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論

阳东县| 乐业县| 康马县| 尉犁县| 德安县| 河源市| 噶尔县| 长乐市| 澎湖县| 上饶县| 兴义市| 察雅县| 舟曲县| 浪卡子县| 环江| 阜新| 县级市| 德安县| 汕尾市| 固阳县| 奉新县| 乐陵市| 辽源市| 绥滨县| 炉霍县| 乡城县| 中卫市| 古田县| 莎车县| 澄城县| 大冶市| 平武县| 鄂托克旗| 阜新市| 仙居县| 类乌齐县| 华容县| 泰和县| 洛隆县| 马山县| 沙洋县|