python正則表達式爬取貓眼電影top100
更新時間:2018年02月24日 15:10:42 作者:sisteryaya
這篇文章主要為大家詳細介紹了python正則表達式爬取貓眼電影top100,具有一定的參考價值,感興趣的小伙伴們可以參考一下
用正則表達式爬取貓眼電影top100,具體內(nèi)容如下
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json # 快速導(dǎo)入此模塊:鼠標先點到要導(dǎo)入的函數(shù)處,再Alt + Enter進行選擇
from multiprocessing.pool import Pool #引入進程池
import requests
import re
import csv
from requests.exceptions import RequestException #引入異常
## 正確保存,無丟失
# 請求一個頁面返回響應(yīng)內(nèi)容
#以《霸王別姬》為列,右擊—查看元素—會顯示一個網(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表出錯
return response.text #返回網(wǎng)頁內(nèi)容
else:return None
except RequestException as e:
return None
# 解析一個頁面
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>')
#寫個正則,匹配所有結(jié)果。這里由上面的網(wǎng)頁相應(yīng)內(nèi)容寫<dd>開頭,.*?匹配任意字符穿 board-index匹配標識符,類名,
# \d 表數(shù)字即排名,'+'表示匹配至少一個可多個數(shù)字,</i>右邊結(jié)束符
#“?”,問號表示 非貪婪匹配,就是一旦匹配到就不在繼續(xù)往后面嘗試。
#而\(和\)分別表示匹配一個“(”和“)”
# re.S匹配多行
regex = re.compile(pattern,re.S) #一個方法,通過一個正則表達式字符串編譯生成一個正則表達式對象,re.S 匹配任意字符
items = regex.findall(html) #以列表形式返回全部能匹配的子串. eg: re.findall(pattern, string[, flags])
for item in items: #將結(jié)果以字典形式返回,鍵值對
yield{ #把這個方法變成一個生成器
'index':item[0],
'image':item[1],
'title':item[2],
'actor':item[3].strip()[3:], #用strip()去掉換行符,不想要 主演: 這三個字就用[3:]組成一個切片,name就可以將前三個字符串去掉
'time':get_release_time(item[4].strip()[5:]), #去掉前五個字符
'area':get_release_area(item[4].strip()[5:]),
'score':item[5]+item[6] #將評分整數(shù)部分和小數(shù)部分結(jié)合起來
}
'''''
#保存到txt,會發(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是一個字典的形式,用json.dumps 把它轉(zhuǎn)換為字符串,再加個換行符
f.close()
#json.dumps :dict 轉(zhuǎn)換為 str
#json.loads: str 轉(zhuǎn)換為 dict
'''
''''''''
# 獲取上映時間 <p class="releasetime">上映時間:1993-01-01(中國香港)</p>
def get_release_time(data):
pattern = '^(.*?)(\(|$)'
regex = re.compile(pattern)
w = regex.search(data)
return w.group(1) # group(1)指的是第一個括號里的東西
# 獲取上映地區(qū)
def get_release_area(data):
pattern = '.*\((.*)\)' #而\(和\)分別表示匹配一個 '(' 和 ')'
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)
# 存儲數(shù)據(jù)
def store_data(item):
with open('movie.csv','a',newline='',encoding='utf-8') as data_csv:
# dialect為打開csv文件的方式,默認是excel,delimiter="\t"參數(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等。
'''''
也可判斷異常,一般沒錯
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)
'''
# 下載封面圖
#讀方式打開的話,并不會新建;寫方式打開的話就會新建。 r只讀,w可寫,a追加
def download_thumb(title,image):
try:
response = requests.get(image)
# 獲取二進制數(shù)據(jù)
with open('image/'+title+'.jpg', 'wb') as f: #將封面圖保存到當前路徑下的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ù)量的進程供用戶調(diào)用,如果有一個新的請求被提交到進程池,進程池還沒有滿,就會創(chuàng)建新的進程來執(zhí)行請求,如果滿了,就先等待
pool.map(main,[i*10 for i in range(10)]) #將數(shù)組中的每一個元素拿出來當做函數(shù)的參數(shù),然后創(chuàng)建一個個的進程,放到進程池里面去運行;第二個參數(shù)是構(gòu)造一個數(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)建一個游標對象
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)建一個游標對象
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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- Python爬蟲入門教程01之爬取豆瓣Top電影
- python使用re模塊爬取豆瓣Top250電影
- 用Python 爬取貓眼電影數(shù)據(jù)分析《無名之輩》
- Python利用Scrapy框架爬取豆瓣電影示例
- Python爬取愛奇藝電影信息代碼實例
- Python實現(xiàn)的爬取豆瓣電影信息功能案例
- python實現(xiàn)的爬取電影下載鏈接功能示例
- Python使用mongodb保存爬取豆瓣電影的數(shù)據(jù)過程解析
- 詳解Python爬取并下載《電影天堂》3千多部電影
- Python爬蟲——爬取豆瓣電影Top250代碼實例
- python使用BeautifulSoup與正則表達式爬取時光網(wǎng)不同地區(qū)top100電影并對比
- python使用requests模塊實現(xiàn)爬取電影天堂最新電影信息
- 一個簡單的python爬蟲程序 爬取豆瓣熱度Top100以內(nèi)的電影信息
- 教你怎么用python爬取愛奇藝熱門電影
相關(guān)文章
python虛擬環(huán)境多種創(chuàng)建方式圖文詳解
創(chuàng)建虛擬環(huán)境是為了讓項目運行在一個獨立的局部的Python環(huán)境中,使得不同環(huán)境的項目互不干擾,這篇文章主要給大家介紹了關(guān)于python虛擬環(huán)境多種創(chuàng)建方式的相關(guān)資料,需要的朋友可以參考下2024-08-08
Python中time.sleep(0.001)是否真的只等待1毫秒
這篇文章主要介紹了Python中time.sleep(0.001)是否真的只等待1毫秒,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06
Python多線程中阻塞(join)與鎖(Lock)使用誤區(qū)解析
這篇文章主要為大家詳細介紹了Python多線程中阻塞join與鎖Lock的使用誤區(qū),具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-04-04
詳解python tkinter包獲取本地絕對路徑(以獲取圖片并展示)
這篇文章主要給大家介紹了關(guān)于python tkinter包獲取本地絕對路徑(以獲取圖片并展示)的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09

