在Python Selenium中遍历列表元素
这是我第一次发帖,所以如果我犯了错误,请让我知道 我正在尝试在Instagram上制作一个有趣的机器人,其中一个功能是进入用户页面,查看他们的关注者,然后开始跟踪列表中的人 这篇文章很相似,但我从中提取的列表在滚动浏览每12个配置文件后会重新填充更多条目 以下是迄今为止的代码:在Python Selenium中遍历列表元素,python,selenium,selenium-webdriver,automation,Python,Selenium,Selenium Webdriver,Automation,这是我第一次发帖,所以如果我犯了错误,请让我知道 我正在尝试在Instagram上制作一个有趣的机器人,其中一个功能是进入用户页面,查看他们的关注者,然后开始跟踪列表中的人 这篇文章很相似,但我从中提取的列表在滚动浏览每12个配置文件后会重新填充更多条目 以下是迄今为止的代码: def follow_multiple(self, user): #navigate to user profile self.nav_user(user) time.sl
def follow_multiple(self, user):
#navigate to user profile
self.nav_user(user)
time.sleep(3)
#open followers window
followers_button = self.driver.find_element_by_xpath("//a[contains(@href, '/{}/followers')]".format(user))
followers_button.click()
time.sleep(2)
followers_popup = self.driver.find_element_by_xpath("/html/body/div[4]/div/div/div[2]")
follower_popup_range = int(self.follower_amt(user))
for i in range(int(follower_popup_range/11)):
time.sleep(random.normalvariate(2, 0.3))
f = 1
while f<=12:
try:
#try to click follow button
time.sleep(random.normalvariate(1.2, 0.2))
lc = f + (i*11)
print('pressing' + str(lc) + '...')
self.driver.find_element_by_xpath("/html/body/div[4]/div/div/div[2]/ul/div/li[{}]/div/div[3]/button"
.format(lc)).click()
print('button ' + str(lc) + ' pressed')
except:
print('button ' + str(lc) + 'failed')
time.sleep(random.normalvariate(0.2, 0.04))
#click cancel
try:
#attempt to click cancel on one xpath
self.driver.find_element_by_xpath("/html/body/div[5]/div/div/div/div[3]/button[2]").click()
print(str(lc) + ': Already following user')
f -= 1
except:
#other xpath for the same button
time.sleep(1)
self.driver.find_element_by_xpath("/html/body/div[5]/div/div/div/div[3]/button[2]").click()
f += 1
#JS to scroll through list
self.driver.execute_script('arguments[0].scrollTop = arguments[0].scrollHeight', followers_popup)
time.sleep(2)
但我不知道为什么,因为元素在那里。非常感谢您的帮助。谢谢 看看这个答案——它是针对Java的,但基本原理是一样的。这回答了你的问题吗?代替使用XPath,考虑使用FiffyEntEngyBySyID或ByuC类,因为像Instagram之类的Web应用程序页面的HTML可以基于用户交互而改变。这可能会导致数据库中出现错误execution@AbdulRauf我尝试用xpath来表示包含文本的按钮,但它一直说按钮在点(x,y)处不可单击,并说正在单击另一个对象。
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document