簡體   English   中英

find_element_by_xpath() 使用 Selenium 和 Python 顯示語法錯誤

[英]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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM