【发布时间】:2020-12-03 09:20:13
【问题描述】:
我正在尝试使用 python selenium 来吸引追随者。但有时python会自行点击。 我想做一个没有错误的程序。我尝试尝试过“try catch”构造,但没有奏效。这是我的代码:
def getFollowers(self):
try:
self.browser.get(f"https://www.instagram.com/{self.username}")
time.sleep(2)
followers=self.browser.find_element_by_xpath("//*[@id='react-root']/section/main/div/header/section/ul/li[2]/a").click()
time.sleep(2)
dialog=self.browser.find_element_by_xpath("/html/body/div[5]/div/div/div[2]")
followerCount=len(dialog.find_elements_by_tag_name("li"))
print(f"first count:{followerCount}")
action=webdriver.ActionChains(self.browser)
//*******************************************Probly my problem is here****************************************
while True:
dialog.click()
action.key_down(Keys.SPACE).key_up(Keys.SPACE).perform()
time.sleep(3)
newCount=len(dialog.find_elements_by_tag_name("li"))
if followerCount!=newCount or newCount==24:
print(f"New count:{newCount}")
time.sleep(3)
followerCount=newCount
else:
break
//**********************************************************************************************************
followers=dialog.find_elements_by_tag_name("li")
followersList=[]
for user in followers:
link=user.find_element_by_css_selector("a").get_attribute("href")
# print(link)
followersList.append(link)
with open("followers.txt","w",encoding="UTF-8") as file:
for item in followersList:
file.write(item+"\n")
time.sleep(5)
except:
pass
我也有 def getfollowing,它完美无缺。如果你愿意,我也可以展示它。但它们几乎相同。
编辑:@RohanShah 解决了我的问题。在页面底部您可以看到解决方案。
编辑:我是新来的,这就是为什么有时我的问题可能毫无意义。但请不要降低我的分数。 Stackoverflow 不会再接受我的问题了。请加分。
【问题讨论】:
-
不清楚“它自己点击”是什么意思。它点击什么?你所说的“本身”是什么意思?
-
我的意思是,在获取用户列表时,点击任何用户会转到他们的页面并完成
-
@RohanShah 感谢您的精彩回答。我现在要检查一下。
-
@RohanShah 它正在工作!你真的拯救了我的一天。我很感激。