用 Scrapy 编写 Instagram 爬虫。我怎样才能进入下一页?

Writing instagram crawler with Scrapy. How can I go to the next page?

作为练习,我决定编写一个 python 脚本来获取指定用户的所有图像。我对 Scrapy 比较熟悉,这就是我选择它作为抓取工具的原因。目前该脚本只能从第一页(最多 12 个)下载图像。

据我所知,instagram 页面是由 javascript 生成的。 Scrapy 的 response.body(类似于从 Chrome 查看的源代码)不像 Chrome 的 Inspector 那样显示 html 结构。在 Chrome 中,在 12 张图像之后,在底部,有一个 link 到下一页的按钮。

例如,instagram.com/instagram. Link to page 2 is instagram.com/instagram/?max_id=1292385931151632610。在第 2 页上有一个 link 到第 3 页 max_id=1287301939457754444

我怎样才能在 Scrapy 中获取那个数字,以便我可以将我的蜘蛛发送到那里? response.body 甚至不包含该数字。还有其他方法可以到达下一页吗?

我知道 Instagram API 会提供一些好处,但我认为没有所有这些令牌也可以做到。

根据 robots.txt 政策,您应该避免抓取 /api//publicapi//query/ 路径,因此请谨慎(负责任地)抓取用户分页。

此外,据我所知,分页以 "Load more" 请求开始,这实际上是一个 https://www.instagram.com/query/ 请求(您需要检查),只有两个必要的值 ownerend_cursor 作为 POST 请求发送。

这些值可以在 '//script[contains(., "sharedData")]/text()'

中的原始请求正文中找到

您还可以添加参数 __a=1(如在 https://www.instagram.com/instagram/?__a=1 中)以仅在 window._sharedData 对象中包含 JSON。

我使用这样的 shell 脚本来做类似的事情:

username=instagram
max=
while :;do
  c=$(curl -s "https://www.instagram.com/$username/?__a=1&max_id=$max")
  jq -r '.user|.id as$user|.media.nodes[]?|$user+" "+.id+" "+.display_src'<<<"$c"
  max=$(jq -r .user.media.page_info.end_cursor<<<"$c")
  jq -e .user.media.page_info.has_next_page<<<"$c">/dev/null||break
done