如何使用 Selenium 处理 Python try/except

时间:2021-04-26 23:57:17

标签: python selenium exception instagram

我正在尝试使用 Selenium 在 Instagram 上关注他人。

但是当迭代所有配置文件以区分公共/私人用户(由页面上的不同元素引起)时,我的大问题是循环。 在我的代码中,当循环到达私人配置文件时,excepttry 之后首先开始。

我的代码:

followers = [ #url of all users]

for follower in followers:
    #Iterate into the list
    browser.get(follower)
    sleep(2)
  
  try:
     browser.find_element_by_css_selector("li:nth-of-type(2) a.-nal3 span").get_attribute("title"):
     print("Public profil") 
     #click on follow                  
  
  except NoSuchElementException:
     print("private profil")
     follower_count = browser.find_element_by_css_selector("li:nth-of-type(2) span.-nal3 span").get_attribute("title")
     if follower_count == 0:
        pass
        print("0 followers")
      
     else:
        print("go follow")

我认为理解正确,如果执行了 except 相应的子句,则在语句 try 之后继续执行,但这并不能解释为什么循环在 except 之后结束。

错误: enter image description here

1 个答案:

答案 0 :(得分:0)

在你的 NoSuchElementException 中,你又在写

     follower_count = browser.find_element_by_css_selector("li:nth-of-type(2) span.-nal3 span").get_attribute("title")

我希望这会引发另一个 NoSuchElementException,因为您再次尝试查找相同的元素。