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

python正則表達(dá)式爬取貓眼電影top100

 更新時(shí)間:2018年02月24日 15:10:42   作者:sisteryaya  
這篇文章主要為大家詳細(xì)介紹了python正則表達(dá)式爬取貓眼電影top100,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

用正則表達(dá)式爬取貓眼電影top100,具體內(nèi)容如下

#!/usr/bin/python 
# -*- coding: utf-8 -*- 
 
import json  # 快速導(dǎo)入此模塊:鼠標(biāo)先點(diǎn)到要導(dǎo)入的函數(shù)處,再Alt + Enter進(jìn)行選擇 
from multiprocessing.pool import Pool #引入進(jìn)程池 
 
import requests 
import re 
import csv 
from requests.exceptions import RequestException #引入異常 
 
## 正確保存,無丟失 
 
# 請求一個(gè)頁面返回響應(yīng)內(nèi)容 
#以《霸王別姬》為列,右擊—查看元素—會(huì)顯示一個(gè)網(wǎng)頁信息 
def get_one_page(url,offset): 
 try: 
  response=requests.get(url=url,params={"offset":offset}) 
  if response.status_code==200: #由狀態(tài)碼判斷返回結(jié)果,200表示請求成功,300,500表出錯(cuò) 
   return response.text #返回網(wǎng)頁內(nèi)容 
  else:return None 
 except RequestException as e: 
   return None 
 
# 解析一個(gè)頁面 
def parse_one_page(html): 
 pattern = ('<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?name"><a' 
       + '.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>' 
       + '.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>') 
 #寫個(gè)正則,匹配所有結(jié)果。這里由上面的網(wǎng)頁相應(yīng)內(nèi)容寫<dd>開頭,.*?匹配任意字符穿 board-index匹配標(biāo)識(shí)符,類名, 
 # \d 表數(shù)字即排名,'+'表示匹配至少一個(gè)可多個(gè)數(shù)字,</i>右邊結(jié)束符 
 #“?”,問號(hào)表示 非貪婪匹配,就是一旦匹配到就不在繼續(xù)往后面嘗試。 
 #而\(和\)分別表示匹配一個(gè)“(”和“)” 
 # re.S匹配多行 
 regex = re.compile(pattern,re.S) #一個(gè)方法,通過一個(gè)正則表達(dá)式字符串編譯生成一個(gè)正則表達(dá)式對(duì)象,re.S 匹配任意字符 
 items = regex.findall(html) #以列表形式返回全部能匹配的子串. eg: re.findall(pattern, string[, flags]) 
 for item in items: #將結(jié)果以字典形式返回,鍵值對(duì) 
   yield{  #把這個(gè)方法變成一個(gè)生成器 
    'index':item[0], 
    'image':item[1], 
    'title':item[2], 
    'actor':item[3].strip()[3:], #用strip()去掉換行符,不想要 主演: 這三個(gè)字就用[3:]組成一個(gè)切片,name就可以將前三個(gè)字符串去掉 
    'time':get_release_time(item[4].strip()[5:]),  #去掉前五個(gè)字符 
    'area':get_release_area(item[4].strip()[5:]), 
    'score':item[5]+item[6] #將評(píng)分整數(shù)部分和小數(shù)部分結(jié)合起來 
  } 
 
''''' 
#保存到txt,會(huì)發(fā)現(xiàn)中文漢字變成了unic的編碼,加上encoding='utf-8',ensure_ascii=False,則漢字可正常輸出 
def write_to_file(content): 
 with open('result.txt','a',encoding='utf-8') as f: # 參數(shù) a ,表示直接往后追加 
  f.write(json.dumps(content,ensure_ascii=False) +'\n') #content是一個(gè)字典的形式,用json.dumps 把它轉(zhuǎn)換為字符串,再加個(gè)換行符 
  f.close()  
#json.dumps :dict 轉(zhuǎn)換為 str 
#json.loads: str 轉(zhuǎn)換為 dict 
''' 
'''''''' 
# 獲取上映時(shí)間 <p class="releasetime">上映時(shí)間:1993-01-01(中國香港)</p> 
def get_release_time(data): 
 pattern = '^(.*?)(\(|$)' 
 regex = re.compile(pattern) 
 w = regex.search(data) 
 return w.group(1) # group(1)指的是第一個(gè)括號(hào)里的東西 
 
# 獲取上映地區(qū) 
def get_release_area(data): 
 pattern = '.*\((.*)\)' #而\(和\)分別表示匹配一個(gè) '(' 和 ')' 
 regex = re.compile(pattern) 
 w = regex.search(data) 
 if w is None: 
  return'未知' 
 return w.group(1) 
 
# 獲取封面大圖,不需要 
# def get_large_thumb(url): 
#  pattern = '(.*?)@.*?' 
#  regex = re.compile(pattern) 
#  w = regex.search(url) 
#  return w.group(1) 
 
# 存儲(chǔ)數(shù)據(jù) 
def store_data(item): 
 with open('movie.csv','a',newline='',encoding='utf-8') as data_csv: 
  # dialect為打開csv文件的方式,默認(rèn)是excel,delimiter="\t"參數(shù)指寫入的時(shí)候的分隔符 
  csv_writer = csv.writer(data_csv) 
  csv_writer.writerow([item['index'], item['image'], item['title'], item['actor'],item['time'],item['area'],item['score']]) 
# 參數(shù)newline是用來控制文本模式之下,一行的結(jié)束字符??梢允荖one,'',\n,\r,\r\n等。 
''''' 
也可判斷異常,一般沒錯(cuò) 
  try: 
   csv_writer = csv.writer(data_csv) 
   csv_writer.writerow([item['index'], item['image'], item['title'], item['actor'],item['time'],item['area'],item['score']]) 
  except Exception as e: 
   print(e) 
   print(item) 
''' 
 
# 下載封面圖 
#讀方式打開的話,并不會(huì)新建;寫方式打開的話就會(huì)新建。 r只讀,w可寫,a追加 
def download_thumb(title,image): 
 try: 
  response = requests.get(image) 
  # 獲取二進(jìn)制數(shù)據(jù) 
  with open('image/'+title+'.jpg', 'wb') as f: #將封面圖保存到當(dāng)前路徑下的image文件夾中,圖片名稱為:電影名.jpg 
   f.write(response.content) 
   f.close() 
 except RequestException as e: 
  print(e) 
  pass 
 
 
# 主調(diào)度程序 
def main(): 
 # 起始URL 
 start_url = 'http://maoyan.com/board/4?' 
 for i in range(0,1000,10): 
  # 獲取響應(yīng)文本內(nèi)容 
  html = get_one_page(url=start_url, offset=i) 
  if html is None: 
   print('鏈接:%s?offset=%s異常'.format(start_url,i)) 
   continue 
  for item in parse_one_page(html): 
   # print(item) 
   store_data(item) 
   # download_thumb(item['title'],item['image']) 
# 
 
if __name__=='__main__': 
 main() 
 
''''' 
if __name__=='__main__': 
 for i in range(10): 
  main(i*10) 
''' 
 
''''' 
if __name__=='__main__': 
 for i in range(10): 
  main(i*10) 
 pool=Pool() #可以提供指定數(shù)量的進(jìn)程供用戶調(diào)用,如果有一個(gè)新的請求被提交到進(jìn)程池,進(jìn)程池還沒有滿,就會(huì)創(chuàng)建新的進(jìn)程來執(zhí)行請求,如果滿了,就先等待 
 pool.map(main,[i*10 for i in range(10)]) #將數(shù)組中的每一個(gè)元素拿出來當(dāng)做函數(shù)的參數(shù),然后創(chuàng)建一個(gè)個(gè)的進(jìn)程,放到進(jìn)程池里面去運(yùn)行;第二個(gè)參數(shù)是構(gòu)造一個(gè)數(shù)組,組成循環(huán) 
 #速度明顯變快!1s 
''' 

保存到數(shù)據(jù)庫

def main(offset): 
  url='http://maoyan.com/board/4?offset='+str(offset) 
  html=get_one_page(url) 
  # for item in parse_one_page(html): 
  #   print(item['number'])  #能正確輸出 , charset="utf8" 
  try: 
    conn = pymysql.connect(host='localhost', user='root', passwd=' ', port=3306,db='test1',charset="utf8",use_unicode = False ) 
    cur = conn.cursor() # 創(chuàng)建一個(gè)游標(biāo)對(duì)象 
    for item in parse_one_page(html): 
      try: 
        # sql = "INSERT INTO movies (number,picture,title,actors,time,area,score) VALUES (%s,%s,%s,%s,%s,%s,%s)" 
        # cur.execute(sql, ( item['number'],item['picture'],item['title'],item['actors'],item['time'],item['area'],item['score'])) 
        sql = "insert into test_movies (number,picture,title,actors,time,area,score) values(%s,%s,%s,%s,%s,%s,%s)" 
        cur.execute(sql, (item['number'], item['picture'], item['title'], item['actors'], item['time'], item['area'],item['score'])) 
      except pymysql.Error as e: 
        print(e) 
      print('- - - - - 數(shù)據(jù)保存成功 - - - - -') 
    conn.commit() 
    cur.close() 
    conn.close() # 關(guān)閉數(shù)據(jù) 
  except pymysql.Error as e: 
    print("Mysql Error %d: %s" % (e.args[0], e.args[1])) 
 
 
if __name__=='__main__': 
  # 連接數(shù)據(jù)庫 
  conn = pymysql.connect(host='localhost', user='root', passwd=' ', port=3306, db='test1', charset="utf8") 
  cur = conn.cursor() # 創(chuàng)建一個(gè)游標(biāo)對(duì)象 
  cur.execute("DROP TABLE IF EXISTS test_movies") # 如果表存在則刪除 
  # 創(chuàng)建表sql語句 
  sqlc = """CREATE TABLE test_movies( 
    number int not null primary key auto_increment, 
    picture VARCHAR(100) NOT NULL, 
    title VARCHAR(100) NOT NULL, 
    actors VARCHAR(200) NOT NULL, 
    time VARCHAR(100) NOT NULL, 
    area VARCHAR(100) , 
    score VARCHAR(50) NOT NULL 
  )""" 
  cur.execute(sqlc) # 執(zhí)行創(chuàng)建數(shù)據(jù)表操作 
  pool=Pool() 
  pool.map(main,[i*10 for i in range(10)]) 

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

相關(guān)文章

  • OpenCV機(jī)器學(xué)習(xí)MeanShift算法筆記分享

    OpenCV機(jī)器學(xué)習(xí)MeanShift算法筆記分享

    這篇文章主要介紹了OpenCV機(jī)器學(xué)習(xí)MeanShift算法筆記分享,有需要的朋友可以借鑒參考下,希望可以對(duì)各位讀者的OpenCV算法學(xué)習(xí)能夠有所幫助
    2021-09-09
  • pycharm激活方法到2099年(激活流程)

    pycharm激活方法到2099年(激活流程)

    這篇文章主要介紹了pycharm激活方法到2099年,文末給大家提到了idea和pycharm最新版激活方法,非常不錯(cuò)對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-09-09
  • Python中Yield的基本用法及Yield與return的區(qū)別解析

    Python中Yield的基本用法及Yield與return的區(qū)別解析

    Python中有一個(gè)非常有用的語法叫做生成器,用到的關(guān)鍵字就是yield,這篇文章主要介紹了Python中Yield的基本用法及Yield與return的區(qū)別,需要的朋友可以參考下
    2022-10-10
  • 最新評(píng)論

    布尔津县| 库车县| 喀喇沁旗| 县级市| 黑龙江省| 南召县| 即墨市| 云浮市| 静乐县| 威信县| 敖汉旗| 白玉县| 江口县| 会理县| 寿阳县| 榆中县| 阿瓦提县| 满洲里市| 新巴尔虎左旗| 长宁区| 隆尧县| 新闻| 余干县| 长泰县| 东宁县| 文水县| 沭阳县| 深泽县| 金秀| 新昌县| 策勒县| 广德县| 南丰县| 潍坊市| 香港 | 澄城县| 拜泉县| 汪清县| 吉安县| 界首市| 沁源县|