在 Python 上抓取

Scraping on Python

我想得到标题,没有。特定用户最近 10 张图像的点赞和评论。 使用下面的代码我只能得到最新的代码。

代码:

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'])

结果: LAST CALL:在今晚的截止日期之前输入今年夏天与奥巴马总统会面的机会。 → Link 在个人资料中。

在下面的代码中,您只检索第一个节点(即第一张图片)。

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'] 

对于这些值的存储,由您决定如何存储它们。