【问题标题】:find_element_by_xpath() shows syntax error using Selenium with Pythonfind_element_by_xpath() 使用 Selenium 和 Python 显示语法错误
【发布时间】:2022-01-11 03:51:38
【问题描述】:

我尝试在 python 中使用 selnium 连接到 Twitter。 我无法使用 Name 或 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()

【问题讨论】:

    标签: python selenium selenium-webdriver xpath


    【解决方案1】:

    您使用了两次双引号。而是将 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()
    

    【讨论】:

      【解决方案2】:

      在构建 时,有两种方法,您可以采用其中任何一种方法:

      • 您需要用双引号(即"...")传递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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-11
        • 1970-01-01
        相关资源
        最近更新 更多