【问题标题】:Scraping on Python在 Python 上抓取
【发布时间】:2016-10-22 13:13:06
【问题描述】:

我想得到标题,不。特定用户最近 10 张图片的点赞数和 cmets 数。 使用下面的代码,我只能得到最新的。

代码:

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

结果: 最后的电话:输入有机会在今晚的截止日期之前在今年夏天与奥巴马总统会面。 → 个人资料中的链接。

【问题讨论】:

    标签: python web-scraping instagram screen-scraping


    【解决方案1】:

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

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

    要获取用户最近 10 张图像的信息,请尝试使用此方法。

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

    要仅打印标题、点赞数和 cmets,请执行此操作。

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

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

    【讨论】:

    • 得到这个:TypeError:列表索引必须是整数,而不是str
    • 我的错。我已经编辑了我的答案。如果更新的答案有效,请告诉我:)
    猜你喜欢
    • 2018-09-01
    • 2017-11-26
    • 1970-01-01
    • 2011-11-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-15
    相关资源
    最近更新 更多