find_element_by_xpath() 在 Python 中使用 Selenium 显示语法错误

find_element_by_xpath() shows syntax error using Selenium with Python

我尝试在 python 中使用 selnium 连接到 Twitter。 我无法使用名称或 Xpath 进行连接。 通过单击检查复制 xpath,然后复制特定元素的 xpath。 我找到的所有关于连接到 Twitter 的教程都是陈旧且无关紧要的。 我在这里附上代码。我在 @id="layers"

上有错误

代码图片:

我很乐意提供帮助。

代码:

from threading import Thread
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from selenium.webdriver.support import wait

driver=webdriver.Chrome(executable_path="C:\Webdrivers\chromedriver.exe")
driver.get("https://twitter.com/i/flow/login")
search=driver.find_element_by_xpath("//*[@id="layers"]/div[2]/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div[1]/div/div[5]/label/div/div[2]/div/input")
search.send_keys("orlaharty1@gmail.com")
button=driver.find_element_by_xpath("//*[@id="layers"]/div[2]/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div[1]/div/div[6]/div")
button.click()

您使用了两次双引号。而是将 xpath 粘贴到单引号 'xpathblabla' 另外,添加 driver.implicity_wait(seconds) 这样如果您的驱动程序正在获取尚未加载的元素,您就不会收到任何错误

driver.get("https://twitter.com/i/flow/login")

#add this line
driver.implicitly_wait(10)
#                                  single quotes
search=driver.find_element_by_xpath('//*[@id="layers"]/div[2]/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div[1]/div/div[5]/label/div/div[2]/div/input')
search.send_keys("orlaharty1@gmail.com")
button=driver.find_element_by_xpath('//*[@id="layers"]/div[2]/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div[1]/div/div[6]/div')
button.click()

构建 时有两种方法,您可以遵循其中的任何一种方法:

  • 您需要用双引号传递 xpath 的值,即 "..." 和单引号中的属性值,即 '...'。例如:

    search=driver.find_element_by_xpath("//*[@attribute_name='attribute_value']")
                             # note the ^double quote & the  ^single quote
    
  • 您需要用单引号传递 xpath 的值,即 '...' 和双引号中的属性值,即 "..."。例如:

    search=driver.find_element_by_xpath('//*[@attribute_name="attribute_value"]')
                             # note the ^single quote & the  ^double quote
    

解决方案

根据上面讨论的上述两个约定,您的有效代码行将是:

driver.get("https://twitter.com/i/flow/login")
search=driver.find_element_by_xpath("//*[@id='layers']/div[2]/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div[1]/div/div[5]/label/div/div[2]/div/input")
search.send_keys("orlaharty1@gmail.com")
button=driver.find_element_by_xpath("//*[@id='layers']/div[2]/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div[1]/div/div[6]/div")
button.click()