我尝试使用 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("[email protected]")
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("[email protected]")
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 时,有两种方法,您可以采用其中任何一种:
您需要用双引号传递 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("[email protected]")
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()
由于 selenium 中 xpath 的用法发生了变化,因此您应该按以下方式使用它。记得在双引号内使用单引号。
from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep
site = webdriver.Edge()
site.get("https://www.test.com")
sleep(15)
email = site.find_element(By.XPATH, "//*[@id='ap_email']")
email.send_keys("[email protected]")