如何通过xpath获取在python上使用selenium的html代码?

2024-09-29 21:38:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个更新按钮,在python中,botı想单击此按钮,但ı尝试了许多选项但不工作ı无法通过XPath定位元素。请帮帮我?谢谢你的帮助

注意:我需要使用文本“更新”来定位,因为网页上有很多按钮

<span class="a-spacing-top-small"> <span class="a-button a-button-primary a-button-small sc-update-link" id="a-autoid-2"> <span class="a-button-inner"> <a href="javascript:void(0);" data-action="update" class="a-button-text" role="button" id="a-autoid-2-announce" style="">Update <span class="aok-offscreen">Nike Academy 18 Rain Jacket Men's (Obsidian, M)</span> </a> </span> </span> </span>

Tags: 定位文本id元素bot选项updatebutton
2条回答

所需元素是启用了JavaScript的元素,因此要在元素上定位/click(),您需要为element_to_be_clickable()诱导WebDriverWait,并且可以使用以下任一Locator Strategies

  • 使用CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span.a-button.a-button-primary.a-button-small.sc-update-link[id^='a-autoid'] a.a-button-text[id$='announce']>span.aok-offscreen"))).click()
    
  • 使用XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[@class='a-button a-button-primary a-button-small sc-update-link' and starts-with(@id,'a-autoid')]//a[@class='a-button-text' and contains(@id,'announce')]/span[@class='aok-offscreen' and starts-with(., 'Nike Academy 18 Rain Jacket Men')]"))).click()
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

这应该起作用:

button = driver.find_element_by_xpath("//a[@data-action,'update']")

其中driver是您的driver实例

相关问题 更多 >

    热门问题