找不到正确的xpath进行转推,或者找不到带有硒的chromedriver和python的按钮

时间:2019-11-23 17:06:10

标签: selenium xpath twitter

我找不到用于转推的正确xpath,就像在此页面上一样:https://twitter.com/snowfulls/status/1198269659465818115

此外,我需要帮助找到第二个转发按钮的xpath,以确认转发。

有没有一种方法可以自动找到xpath?

1 个答案:

答案 0 :(得分:1)

要回答第一个问题-不,除非您使用某种扫描仪工具,否则无法自动找到XPath。这些XPath并不总是准确的。最好的方法是使用XPath浏览器扩展助手,该助手将允许您实时测试页面上的XPath表达式。这就是我用来帮助开发解决方案的方法。

要在推特上单击“赞”按钮,可以使用以下代码:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# ensure the above references are added to use WebDriverWait correctly

# wait for the element to exist
like_button = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//div[@aria-label='Like']")))

# click the like button
like_button.click()

要单击“转发”按钮,类似地:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# ensure the above references are added to use WebDriverWait correctly


# wait for the element to exist
retweet_button = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//div[@aria-label='Retweet']")))

# click the retweet button
retweet_button.click()

# now, confirm the retweet:
retweet_confirm = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//div[@data-testid='retweetConfirm']")))

# click the retweet confirm button
retweet_confirm.click()

上述解决方案使用了Selenium库的一些简单扩展-主要是WebDriverWaitExpectedConditions类。 WebDriverWait允许我们等待指定的时间,以便条件发生。这与ExpectedConditions类紧密结合,该类测量页面上元素的状态以确认WebElement是否满足特定条件。

因此,WebDriverWait(driver, 10).until(EC.presence_of_element_located的意思是“等待最多10秒钟以等待WebElement的出现” –然后在定位器策略WebElement中指定此By.XPath, "...."

希望这种解释有所帮助。