我找不到用于转推的正确xpath,就像在此页面上一样:https://twitter.com/snowfulls/status/1198269659465818115
此外,我需要帮助找到第二个转发按钮的xpath,以确认转发。
有没有一种方法可以自动找到xpath?
答案 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库的一些简单扩展-主要是WebDriverWait
和ExpectedConditions
类。 WebDriverWait
允许我们等待指定的时间,以便条件发生。这与ExpectedConditions
类紧密结合,该类测量页面上元素的状态以确认WebElement
是否满足特定条件。
因此,WebDriverWait(driver, 10).until(EC.presence_of_element_located
的意思是“等待最多10秒钟以等待WebElement的出现” –然后在定位器策略WebElement
中指定此By.XPath, "...."
。
希望这种解释有所帮助。