我正在尝试构建一个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
谢谢大家!
我无法回答为什么您的绝对路径无效。您最好尝试这样的相对路径:
self.browser.find_elements_by_xpath("//a[@class='sqdOP yWX7d _8A5w5 ZIAjV ']")
这样,您就可以删除所有可用的注释并将其作为列表进行处理。这段代码寻找elementSSS!不是元素。
list = self.browser.find_elements_by_xpath("//a[@class='sqdOP yWX7d _8A5w5 ZIAjV ']")
for x in list:
x.click()
# do STUFF
[我在一个非常高级的Instagram Bot上工作,我可以说,如果您这样输入数字,Instagram将很快被Bot检测到。尝试更多随机的东西并添加:
import time
import random
time.sleep(random.uniform(1,3))
这样,您可以在两次操作之间创建长短间隔。