首页 > 解决方案 > 硒元素选择:Instagram 评论

问题描述

我正在尝试构建一个 python 脚本,该脚本将喜欢对我的图片发表评论的每个人的 10 张图片,但我的选择器效果不佳。

这是我的代码:

## url of the insta photo
url = 'https://www.instagram.com/p/B_cyBxwBDyd/'
driver.get(url)
sleep(randint(15,20))
# start at the first comment and end at the 10th comment
n = 1
while n <= 10:

    ## get username and click on it
    username_button = driver.find_element_by_xpath('/html/body/div[4]/div[2]/div/article/div[2]/div[1]/ul/ul['
                                                   + str(n) + ']/div/li/div/div[1]/div[1]/a')

    username_button.click()

    ## click on the username's first photo and repeat the process for 10 phots
    for x in range(0,10):
        photo =  driver.find_element_by_xpath('//*[@id="react-root"]/section/main/div/div[3]/article/div[1]/div/div[1]/div[1]')
        photo.click()

        button_like = driver.find_element_by_xpath('/html/body/div[4]/div[2]/div/article/div[2]/section[1]/span[1]/button')
        button_like.click()
## comment on a few of the photos, set up a probability scheme so not all the photos get a comment
        comm_prob = randint(1,10)
        print('{}_{}: {}'.format(x, n,comm_prob))
        if comm_prob > 3:
            comments += 1
            sleep(randint(15,28))
            driver.find_element_by_xpath('/html/body/div[4]/div[2]/div/article/div[2]/section[1]/span[2]/button').click()

            comment_box = driver.find_element_by_xpath('/html/body/div[4]/div[2]/div/article/div[2]/section[3]/div/form/textarea')
            if (comm_prob == 4):
                comment_box.send_keys('OMG amazing!')
                sleep(1)
            elif (comm_prob == 5):
                comment_box.send_keys('absolutely flawless!!')
                sleep(1)
            elif (comm_prob == 6):
                comment_box.send_keys('OMG obcessed')
            elif (comm_prob == 7):
                comment_box.send_keys('so pretty!!')
                sleep(1)
            elif comm_prob == 8:
                comment_box.send_keys('I love this!!')
                sleep(1)
            elif comm_prob == 9:
                comment_box.send_keys('I love this shot (:')
                sleep(1)
            elif comm_prob == 10:
                comment_box.send_keys('perfect!')
                sleep(1)
            # Enter to post comment
            comment_box.send_keys(Keys.ENTER)
            sleep(randint(15,28))

        driver.find_element_by_link_text('Next').click()

    ## back to the comments page

    driver.get(url)

    n += 1

我得到错误:

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[4]/div[2]/div/article/div[2]/div[1]/ul/ul[1]/div/li/div/div[1]/div[1]/a"}

但是,当我从第一条评论中复制 xpath 时,它是:

/html/body/div[4]/div[2]/div/article/div[2]/div[1]/ul/ul[1]/div/li/div/div[1]/div[1]/a

所以我不确定为什么它无法找到元素?

这是页面检查的屏幕截图: screenshot

谢谢大家!

标签: pythonhtmlcssseleniuminstagram

解决方案


推荐阅读