python爬取貓眼電影排名
本次爬蟲主要使用requests庫爬取和正則表達(dá)式re解析,下面進(jìn)行簡要分析
1、項(xiàng)目流程
1、獲取貓眼電影排行榜一頁的頁面信息,通過requests.get獲得
2、使用正則表達(dá)式解析一個(gè)頁面的頁面信息,獲得需要內(nèi)容
3、通過生成器爬取多個(gè)頁面內(nèi)容,輸出
4、將所得到內(nèi)容存入字典中,輸出
5、將所得到信息存儲(chǔ)到MongoDB數(shù)據(jù)庫中
2、項(xiàng)目結(jié)果
成功爬取,存入mongodb數(shù)據(jù)庫
mongodb查詢
3、項(xiàng)目代碼
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#作者:nuancolor
#網(wǎng)址:暫無
import requests
from requests.exceptions import RequestException
import re
import pymongo
# 配置數(shù)據(jù)庫信息
MONGO_HOST = "127.0.0.1" # 主機(jī)IP
MONGO_URl = 'localhost'
MONGO_DB = 'test' # 數(shù)據(jù)庫名
MONGO_TABLE = 'movies' # 表名
# 連接數(shù)據(jù)庫
client = pymongo.MongoClient(MONGO_URl)
db = client[MONGO_DB]
# 存入數(shù)據(jù)庫
def save_url_to_Mongo(result):
try:
if db[MONGO_TABLE].insert_one(result):
print('存儲(chǔ)到MongoDB成功', result)
except Exception:
print('存儲(chǔ)到MongoDb失敗', result)
# 獲取
def get_one_page(url):
try:
response = requests.get(url)
if response.status_code == 200:
return response.text
return None
except RequestException:
return None
# 解析
def parse_one_page(html):
pattern = re.compile('
.*?board-index.*?>(\d+).*?
'
+ '
(.*?)
.*?star">(.*?)
'
+ '.*?>(.*?)
.*?integer">(.*?)'
+ '.*?fraction">(.*?).*?
', re.S)
items = re.findall(pattern, html)
# 以字典的形式存儲(chǔ)起來
headurl = 'https://maoyan.com'
for item in items:
yield {
'index': item[0],
'url': headurl + item[1],
'title': item[2],
'actor': item[3].strip()[3:],
'time': item[4].strip()[5:],
'score': item[5] + item[6]
}
def main(offset):
url = 'https://maoyan.com/board/4?offset=' + str(offset)
html = get_one_page(url)
for item in parse_one_page(html):
print(item)
result = item
save_url_to_Mongo(result)
if __name__ == '__main__':
for i in range(3):
main(i * 10)
4、遇到的問題及解決
1、進(jìn)行頁面解析是書寫正則表達(dá)式一定要規(guī)范,不然會(huì)出現(xiàn)報(bào)錯(cuò)或解析內(nèi)容為空列表
2、爬取電影的url發(fā)現(xiàn)頁面只爬取到網(wǎng)頁鏈接的后半部分,在進(jìn)行數(shù)據(jù)處理是進(jìn)行相應(yīng)補(bǔ)充即可
3、連接pymongo是報(bào)錯(cuò),沒有發(fā)現(xiàn)該庫,我使用的是spyder運(yùn)行項(xiàng)目,換pycharm部署之后成功。
小結(jié)
本次項(xiàng)目主要是對(duì)requests庫和re庫的一個(gè)熟練使用,途中出現(xiàn)的問題等都加深了對(duì)爬蟲處理的理解與應(yīng)用。
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
