- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我想使用 Python 从公共(public) Instagram 帐户中抓取所有帖子,以进行我在大学进行的一项研究。然而,我开始感到沮丧,因为我无法从 Instagram 中提取超过 12 条帖子。
Selenium 完成了滚动页面的工作,并且我已经让 beautifulsoup 以适当的方式解析我想要的数据,尽管仅适用于前十二篇文章。到目前为止,我已经尝试了几种不同的方法,但开始感到陷入困境。我在这里查看了几个教程和线程,例如:
How do I scrape a full instagram page in python?
Web Scraping with Selenium Python [Twitter + Instagram]
https://michaeljsanders.com/2017/05/12/scrapin-and-scrollin.html
https://edmundmartin.com/scraping-instagram-with-python/
感谢大家的回复!
最诚挚的问候,卡勒。
我尝试过的代码。示例1:
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):
print('[+] Downloading:\n')
c = webdriver.Chrome()
c.get("https://www.instagram.com/frank_the_carden/")
lenOfPage = c.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
match=False
while(match==False):
lastCount = lenOfPage
time.sleep(2)
lenOfPage = c.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
if lastCount==lenOfPage:
match=True
soup = BeautifulSoup(c.page_source, 'lxml')
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']
caption = post['node']['edge_media_to_caption']
print('Post on :',datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S'))
print('Liked by :',likedby)
print('comments :',comments)
print('caption :',caption)
def main(self):
self.ctx = ssl.create_default_context()
self.ctx.check_hostname = False
self.ctx.verify_mode = ssl.CERT_NONE
with open("accounts.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()
示例2:
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
import json
from datetime import datetime
c = webdriver.Chrome()
c.get("https://www.instagram.com/frank_the_carden/")
time.sleep(1)
elem = c.find_element_by_tag_name("body")
no_of_pagedowns = 20
while no_of_pagedowns:
elem.send_keys(Keys.PAGE_DOWN)
time.sleep(0.2)
no_of_pagedowns-=1
soup = BeautifulSoup(c.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)
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']
caption = post['node']['edge_media_to_caption']
print('Post on :',datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S'))
print('Liked by :',likedby)
print('comments :',comments)
print('caption :',caption)
示例 3:
import time
import json
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
from datetime import datetime
import requests
import urllib3
browser = webdriver.Chrome()
media_url = 'https://www.instagram.com/graphql/query/?query_hash=42323d64886122307be10013ad2dcc44&variables={"id":"%s","first":50,"after":"%s"}'
browser = webdriver.Chrome()
# first get https://instagram.com to obtain cookies
browser.get('https://www.instagram.com/frank_the_carden/')
browser_cookies = browser.get_cookies()
# set a session with cookies
session = requests.Session()
for cookie in browser_cookies:
c = {cookie['name']: cookie['value']}
session.cookies.update(c)
# get response as JSON
response = session.get(media_url % ('5719699176', ''), verify=False).json()
time.sleep(1)
elem = browser.find_element_by_tag_name("body")
no_of_pagedowns = 20
while no_of_pagedowns:
elem.send_keys(Keys.PAGE_DOWN)
time.sleep(0.2)
no_of_pagedowns-=1
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)
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']
caption = post['node']['edge_media_to_caption']
print('Post on :',datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S'))
print('Liked by :',likedby)
print('comments :',comments)
print('caption :',caption)
示例 4:
from random import choice
import json
import time
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
browser = webdriver.Chrome()
browser.get("https://www.instagram.com/frank_the_carden/")
# Selenium script to scroll to the bottom
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(1)
lenOfPage = browser.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
if lastCount==lenOfPage:
match=True
_user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'
]
class InstagramScraper:
def __init__(self, user_agents=None, proxy=None):
self.user_agents = user_agents
self.proxy = proxy
def __random_agent(self):
if self.user_agents and isinstance(self.user_agents, list):
return choice(self.user_agents)
return choice(_user_agents)
def __request_url(self, url):
try:
response = requests.get(url, headers={'User-Agent': self.__random_agent()}, proxies={'http': self.proxy,
'https': self.proxy})
response.raise_for_status()
except requests.HTTPError:
raise requests.HTTPError('Received non 200 status code from Instagram')
except requests.RequestException:
raise requests.RequestException
else:
return response.text
@staticmethod
def extract_json_data(html):
soup = BeautifulSoup(html, 'html.parser')
body = soup.find('body')
script_tag = body.find('script')
raw_string = script_tag.text.strip().replace('window._sharedData =', '').replace(';', '')
return json.loads(raw_string)
def profile_page_metrics(self, profile_url):
results = {}
try:
response = self.__request_url(profile_url)
json_data = self.extract_json_data(response)
metrics = json_data['entry_data']['ProfilePage'][0]['graphql']['user']
except Exception as e:
raise e
else:
for key, value in metrics.items():
if key != 'edge_owner_to_timeline_media':
if value and isinstance(value, dict):
value = value['count']
results[key] = value
elif value:
results[key] = value
return results
def profile_page_recent_posts(self, profile_url):
results = []
try:
response = self.__request_url(profile_url)
json_data = self.extract_json_data(response)
metrics = json_data['entry_data']['ProfilePage'][0]['graphql']['user']['edge_owner_to_timeline_media']["edges"]
except Exception as e:
raise e
else:
for node in metrics:
node = node.get('node')
if node and isinstance(node, dict):
results.append(node)
return results
from pprint import pprint
k = InstagramScraper()
results = k.profile_page_recent_posts('https://www.instagram.com/frank_the_carden/')
pprint(results)
最佳答案
我会直接调用 instagram graph ql api,就像您在“示例 3”中所做的那样。我有一个工作代码,但他们改变了 query_hash 的生成方式,我无法让它工作,但您可能也面临同样的问题。
除此之外,我目前正在使用此 python client 抓取 Instagram 数据。 。但您需要提供 Instagram 凭据才能正常工作。
关于python - 无法在 Instagram 公共(public)帐户上抓取超过 12 个帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59562894/
如本answer所述,如果浏览器不支持 e,可以设置后备游标。 G。 光标:抓取;。我现在的问题是获取这些图像。在我的驱动器上本地搜索“.cur”只给了我系统光标,其中 grab.cur 和 grab
以下代码在计算机上运行以从 Instagram 帐户中抓取数据。当我尝试在 VPS 服务器上使用它时,我被重定向到 Instagram 登录页面,因此脚本不起作用。 为什么当我在电脑上或服务器上时,I
我在使用 Ruby 和 Mechanize 将 POST 查询传递到站点的网站上。访问站点的查询基于 firebug,如下所示 param.PrdNo=-1¶m.Type=Prop¶m
我正在尝试抓取一个具有多个页面结果的网站,例如“1、2、3、4、5...”。 每个分页号都是到另一个页面的链接,我需要抓取每个页面。 到目前为止,我想出了这个: while lien = page.l
我正在使用 HtmlAgilityPack 在 C# Asp.Net 中执行 Scraping,到目前为止,我在从多个 Web 执行 Scratch 时没有遇到问题,但是,尝试弹出以下代码时出现错误
如果我有一个 css 文件做这样的事情 #foo:after{content:"bar;} ,有没有办法用 javascript 获取 :after 的内容?获取父元素的内容只返回 #foo 元素的内
问题是这样的: 我有一个 Web 应用程序 - 一个经常更改的通知系统 - 在一系列本地计算机上运行。该应用程序每隔几秒刷新一次以显示新信息。计算机仅显示信息,没有键盘或任何输入设备。 问题是,如果与
我想制作一个程序来模拟用户浏览网站和点击链接。必须启用 Cookie 和 javascript。我已经在 python 中成功地做到了这一点,但我想把它写成一种可编译的语言(python ide 不会
我制作了这个小机器人,它通过搜索参数列表进行处理。它工作正常,直到页面上有几个结果: product_prices_euros 给出了一半为空的项目列表。因此,当我与 product_prices_c
我需要找到一个单词的匹配项,例如: 在网上找到所有单词“学习”https://www.georgetown.edu/(结果:4个字)(您可以看到它按CTRL + F并搜索) 我有我的 Python 代
有一个站点\资源提供一些一般统计信息以及搜索工具的界面。这种搜索操作成本高昂,因此我想限制频繁且连续(即自动)的搜索请求(来自人,而不是来自搜索引擎)。 我相信有很多现有的技术和框架可以执行一些情报抓
这并不是真正的抓取,我只是想在网页中找到类具有特定值的 URL。例如: 我想获取 href 值。关于如何做到这一点的任何想法?也许正则表达式?你能发布一些示例代码吗?我猜 html 抓取库,比如 B
我正在使用 scrapy。 我正在使用的网站具有无限滚动功能。 该网站有很多帖子,但我只抓取了 13 个。 如何抓取剩余的帖子? 这是我的代码: class exampleSpider(scrapy.
我正在尝试从这个 website 中抓取图像和新闻 url .我定义的标签是 root_tag=["div", {"class":"ngp_col ngp_col-bottom-gutter-2 ng
关闭。这个问题需要更多focused .它目前不接受答案。 想改进这个问题吗? 更新问题,使其只关注一个问题 editing this post . 关闭上个月。 Improve this ques
我在几个文件夹中有数千个 html 文件,我想从评论中提取数据并将其放入 csv 文件中。这将允许我为项目格式化和清理它。例如,我在这个文件夹中有 640 个 html 文件: D:\My Web S
我在编写用于抓取网页的实用程序时遇到了一个问题。 我正在发送 POST 请求来检索数据,我模仿我正在抓取的网络行为(根据使用 fiddler 收集的信息)。 我已经能够自动替换我的 POST 中除 V
对于 Googlebot 的 AJAX 抓取,我在我的网站中使用“_escaped_fragment_”参数。 现在我查看了 Yandex 对我网站的搜索结果。 我看到搜索结果中不存在 AJAX 响应
我正在尝试抓取网站的所有结果页面,它可以工作,但有时脚本会停止并显示此错误: 502 => Net::HTTPBadGateway for https://website.com/id/12/ --
我是一个学习网络爬虫的初学者,由于某种原因我无法爬网this地点。当我在 Chrome 中检查它时,代码看起来不错,但是当我用 BeautifulSoup 阅读它时,它不再是可刮的。汤提到“谷歌分析”
我是一名优秀的程序员,十分优秀!