【问题标题】:Finding post+comment block on instagram (selenium, python, chromedriver)在 instagram 上查找 post+comment 块(selenium、python、chromedriver)
【发布时间】:2020-04-01 03:33:40
【问题描述】:

我的目标是能够在页面上找到我关注的所有 Instagram(帖子+评论)用户块的大小和位置。 (下方页面大矩形块,左边是图片,右边是cmets)

一个例子如下:

  1. 转到https://www.instagram.com/zuck/

  2. 点击第一个帖子

  1. 我正在尝试driver.find_element 上面页面中心带有 cmets 块的图像,以便我可以在块的页面上找到大小和位置。我看到的 xpath 是 (//*[@id="react-root"]/section/main/div/div/article/div[1]) 并且 div 类以 _97aPb 开头,但是,当我刷新或转到其他用户时,这些会发生变化。

所以,我正在寻找另一种方法来找到该元素。我希望能够点击下一篇文章并能够找到所有帖子的(帖子+评论)块。

【问题讨论】:

    标签: python selenium selenium-chromedriver


    【解决方案1】:

    文章获取方式:

    根据帖子的打开方式,内容将在带有@role="dialog"@id="react-root" 的div 下。如果您直接打开帖子,则没有对话框,但如果您搜索'//div[@role="dialog" or @id="react-root"]//article,那么最后一个将是您要查找的帖子。

    所以:

    article = driver.find_elements_by_xpath('//div[@role="dialog" or @id="react-root"]//article')[-1]
    

    如何获取文章中的下一张图片:

    next_image_arrow = article.find_element_by_xpath('.//*[contains(@class, "coreSpriteRightChevron")]')
    

    如何选择下一篇文章(仅当文章以模态打开时可用):

    next_article_button = driver.find_element_by_xpath('//a[contains(@class, "coreSpriteRightPaginationArrow")]')
    

    如何获得cmets:

    all_comments = article.find_elements_by_xpath('./div/section[2]/following-sibling::div/ul/ul')
    

    上面的 Xpath 是这个意思:

    • /div/section[2]直接div子节点且至少有2个直接section标记子节点的节点并选择第二个
    • /following-sibling::div/ul/ul

    我希望这能回答这个问题。

    【讨论】:

    • 感谢您的回复和解释。我按照您的建议单击右箭头查看所有帖子,因此我以与上图类似的视图查看所有帖子。我试过 article = driver.find_element_by_xpath('//div[@role="dialog" or @id="react-root"]//article')[-1],但我得到一个错误 TypeError: 'WebElement' object不可下标。所以我尝试了 article = driver.find_element_by_xpath(('//div[@role="dialog" or @id="react-root"]//article')[-1]),但后来我得到了一个错误没有这样的元素。
    • 我尝试检查页面并粘贴 '//div[@role="dialog" 或 @id="react-root"]//article'。我看到了两个匹配项,第二个是帖子的图像。所以不知道为什么找不到元素。
    • 我的错误应该是find_elements_by_xpath。现在修复答案。
    • 谢谢!还有一个问题:我正在尝试通过阅读 selenium api 并查看有关堆栈溢出的其他问题来截取这些元素的屏幕截图,我不明白为什么这不起作用:article.screenshot_as_png('article.png') all_cmets。 screenshot_as_png('cmets.png') 非常感谢您的帮助。谢谢。
    • all_comments.screenshot_as_png article.screenshot_as_png('article.png')
    猜你喜欢
    • 2019-11-13
    • 2022-01-10
    • 2017-02-09
    • 1970-01-01
    • 2017-04-24
    • 2020-12-22
    • 1970-01-01
    • 2020-07-15
    相关资源
    最近更新 更多