2016-06-21 43 views
3

我想獲得的標題,沒有。最近的10個特定用戶的圖像的喜歡和評論。 使用下面的代碼,我只是能得到最新的一個。刮Python的

代碼:

from selenium import webdriver 
from bs4 import BeautifulSoup 
import json, time, re 
phantomjs_path = r'C:\Users\ravi.janjwadia\Desktop\phantomjs-2.1.1-windows\bin\phantomjs.exe' 
browser = webdriver.PhantomJS(phantomjs_path) 
user = "barackobama"  
browser.get('https://instagram.com/' + user) 
time.sleep(0.5) 
soup = BeautifulSoup(browser.page_source, 'html.parser') 
script_tag = soup.find('script',text=re.compile('window\._sharedData')) 
shared_data = script_tag.string.partition('=')[-1].strip(' ;') 
result = json.loads(shared_data) 
print(result['entry_data']['ProfilePage'][0]['user']['media']['nodes'][0]['caption']) 

結果: 最後一次通話:輸入一個機會,今晚的最後期限前,以滿足奧巴馬總統今年夏天。 →在配置文件中鏈接。

回答

3

在下面的代碼,你只取回第一個節點(這是第一個圖像)。

print(result['entry_data']['ProfilePage'][0]['user']['media']['nodes'][0]['caption']) 

要獲取用戶的最近10張圖片的信息,請嘗試此操作。

recent_ten_nodes = result['entry_data']['ProfilePage'][0]['user']['media']['nodes'][:10] 

要只打印字幕,喜歡和評論的數量做到這一點。

for node in recent_ten_nodes: 
    print node['caption'] 
    print node['likes']['count'] 
    print node['comments']['count'] 

爲了存儲這些值,由您來決定如何存儲它們。

+0

聞聽此事: 類型錯誤:列表索引必須是整數,而不是str的 – Ravi

+0

我的壞。我編輯了我的答案。不要讓我知道如果更新的答案工程:) –

+0

謝謝。它的工作完美 – Ravi