找不到包含selenium python的按钮

2024-10-02 12:29:43 发布

您现在位置:Python中文网/ 问答频道 /正文

前几天我遇到了一个类似的问题,我通过使用xpath解决了这个问题,因为我要查找的元素不在原始URL中

我正在尝试制作一个脚本,以便在instagram上对某人展开跟踪,并且我能够进入他们的个人资料页面——这只是找到按钮的问题。我尝试过使用xpath和css选择器

driver = webdriver.Chrome('C:\*\chromedriver.exe')
driver.get("https://www.instagram.com/accounts/login/")

elem2 = driver.find_element_by_name("username")
elem2.send_keys('*')
elem3 = driver.find_element_by_name("password")
elem3.send_keys('*')
elem3.send_keys(Keys.ENTER)
while True:
    try:
        elem4 = driver.find_element_by_css_selector(".-Cab_, .bIiDR")
        elem4.click()
        break
    except Exception:
        pass


names = ['chucknorris']
for i in names:
    elem5 = driver.find_element_by_xpath('//*[@id="react-root"]/section/nav/div[2]/div/div/div[2]/input')   
    elem5.send_keys(i)
    time.sleep(1)
    while True:
        try:
            elems = driver.find_elements_by_class_name("yCE8d")
            elems[0].click()
            break
        except Exception:
            pass

##    while True:
##        try:
##            elemL = driver.find_elements_by_xpath('//*[@id="react-root"]/section/main/div/header/section/div[2]/div/span/span[1]')
##        except Exception:
##            pass
#This part was just so I got the error message rather than infinite loop of nothing
    time.sleep(4)
    elemL = driver.find_element_by_xpath('//div[@id="react-root"]/section/main/div/header/section/div[2]/div/span/span[1]/button')
    elemL.click()

“elemL”是所需的按钮元素


Tags: namedivsendtruebydriversectionelement
2条回答

我的答案是使用driver.find_element_by_css_selector('.-fzfL')这是一个有背景色属性等(真的不知道这是否重要)

最初的xpath失败有两个原因。你知道吗

  1. id为“react root”的元素是一个span而不是div(它在另一个xpath中工作,因为您有一个*)
  2. section元素下的子div是第一个div,而不是第二个div。你知道吗

另一种选择是这样做(如果您确信按钮的文本不会经常更改:

driver.find_element_by_xpath('//*[@id="react-root"]//main//button[.="Following"]')

相关问题 更多 >

    热门问题