【问题标题】:Instagram web scraping with selenium Python problem使用 selenium Python 问题进行 Instagram 网页抓取
【发布时间】:2021-05-28 08:14:19
【问题描述】:

我在从 Instagram 个人资料中抓取所有图片时遇到问题,我将页面滚动到底部,然后找到所有“a”标签,最后总是我只得到最后 30 个图片链接。我认为该驱动程序没有看到页面的全部内容。

#scroll
scrolldown = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var scrolldown=document.body.scrollHeight;return scrolldown;")
match=False
while(match==False):
    last_count = scrolldown
    time.sleep(2)
    scrolldown = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var scrolldown=document.body.scrollHeight;return scrolldown;")
    if last_count==scrolldown:
        match=True

#posts
posts = []
time.sleep(2)
links = driver.find_elements_by_tag_name('a')
time.sleep(2)
for link in links:
    post = link.get_attribute('href')
    if '/p/' in post:
        posts.append(post)

【问题讨论】:

  • 您的驱动程序滚动是否正确?
  • 是的,滚动效果很好,我总是得到最后 30 个帖子 - 表示最旧的 30 个帖子
  • 那么向下滚动变量是什么样的?也许您可以像下面那样获取链接,并比较 len(links) 与 len(old_links) 以了解何时没有获得更多链接,类似于您尝试使用 last_count vs scrolldown
  • 感谢您的提示;)我解决了问题 - 在循环“for”中使用函数

标签: python selenium web instagram screen-scraping


【解决方案1】:

看起来您首先滚动到页面底部,然后才获取链接,而不是获取链接并在滚动循环中处理它们。
所以,如果你想获得所有的链接,你应该执行

links = driver.find_elements_by_tag_name('a')
time.sleep(2)
for link in links:
    post = link.get_attribute('href')
    if '/p/' in post:
        posts.append(post)

在滚动内部,也在第一次滚动之前。
像这样的:

def get_links():
    time.sleep(2)
    links = driver.find_elements_by_tag_name('a')
    time.sleep(2)
    for link in links:
        post = link.get_attribute('href')
        if '/p/' in post:
            posts.add(post)

posts = set()
get_links()
scrolldown = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var scrolldown=document.body.scrollHeight;return scrolldown;")
match=False
while(match==False):
    get_links()
    last_count = scrolldown
    time.sleep(2)
    scrolldown = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var scrolldown=document.body.scrollHeight;return scrolldown;")
    if last_count==scrolldown:
        match=True

【讨论】:

  • 非常感谢,您的解决方案效果很好。为了避免重复链接,我使用了 posts = set() 而不是 posts = []
  • 对!大修正!我会更新答案。
  • 当然,更新 posts.append -> posts.add ;)
猜你喜欢
  • 2017-08-19
  • 2021-11-02
  • 2021-05-08
  • 2018-07-20
  • 2020-03-13
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
相关资源
最近更新 更多