python - 用python抓取instagram个人资料
问题描述
我正在尝试从给定 instagram 个人资料上的每个帖子中汇总一些数据。
我混合了在这里和那里找到的代码,并决定使用 selenium 来加载和滚动页面,并使用 BeautifulSoup 来解析数据。
不幸的是,即使我用硒加载了整个页面,我也只能访问前十二个帖子......
我试图在整页加载结束时甚至在每次滚动之间解析 html,结果相同。
这是我的代码,它在 users.txt 文件中加载 instagram 用户名,随意放置您喜欢的帐户并尝试(它必须有超过 12 个帖子才能看到行为,但如果您希望它快一点,则不需要那么多) ..
#!/usr/bin/python
# -*- coding: utf-8 -*-
import requests
import urllib.request
import urllib.parse
import urllib.error
from bs4 import BeautifulSoup
import ssl
import json
import time
from selenium import webdriver
from datetime import datetime
class Insta_Image_Links_Scraper:
def getlinks(self, user, url):
browser = webdriver.Chrome()
browser.get(url)
lenOfPage = browser.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
match=False
while(match==False):
lastCount = lenOfPage
time.sleep(3)
lenOfPage = browser.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
if lastCount==lenOfPage:
match=True
soup = BeautifulSoup(browser.page_source, 'html.parser')
body = soup.find('body')
script = body.find('script')
page_json = script.text.strip().replace('window._sharedData =', '').replace(';', '')
data = json.loads(page_json)
print ('Scraping posts for user ' + user+"...........")
for post in data['entry_data']['ProfilePage'][0]['graphql']['user']['edge_owner_to_timeline_media']['edges']:
timestamp = post['node']['taken_at_timestamp']
likedby = post['node']['edge_liked_by']['count']
comments = post['node']['edge_media_to_comment']['count']
isVideo = post['node']['is_video']
print('Post on :',datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S'))
def main(self):
self.ctx = ssl.create_default_context()
self.ctx.check_hostname = False
self.ctx.verify_mode = ssl.CERT_NONE
with open('users.txt') as f:
self.content = f.readlines()
self.content = [x.strip() for x in self.content]
for user in self.content:
self.getlinks(user,
'https://www.instagram.com/'
+ user + '/')
if __name__ == '__main__':
obj = Insta_Image_Links_Scraper()
obj.main()
它应该在用户个人资料上输出每个帖子的时间戳,而不仅仅是与您在不滚动时看到的内容相对应的第一个帖子。
谢谢 !
解决方案
推荐阅读
- matlab - Matlab循环遍历不结合csv的文件
- c# - jquery导致错误:单击没有代码的东西时未定义
- python - 扩展熊猫数据框
- excel - 如何将以下 excel 数据复制到不同的工作簿并提示用户保存?
- c# - 在单元测试中同时使用不同参数的多个 Web-API 请求
- powershell - 通过符号名称(键)访问脚本的多个输出
- sql - SQL - 遍历行两次并追溯更改值
- c# - 使用 Windows 服务运行时,Web 服务引用不起作用?
- visual-studio - Visual Studio2017 - 生产力工具
- javascript - 在 chart.js 中为多轴折线图使用自定义数据格式