WebElement上的Selenium WebDriver“ find_element_by_xpath”

时间:2019-12-13 11:15:46

标签: python html selenium

<figcaption class="ncss-row">
   <div class="ncss-col-sm-12 full">
     <div class="figcaption-content">
       <div class="copy-container ta-sm-c bg-white pt6-sm pb7-sm pb5-lg">
         <h3 class="ncss-brand u-uppercase text-color-grey mb-1-sm mb0-md mb-3-lg fs12-sm fs14-md">
          Air Jordan XI<!-- -->&nbsp;
         </h3>
         <h6 class="ncss-brand u-uppercase fs20-sm fs24-md fs28-lg">Black/Red<!-- -->&nbsp;
         </h6>
       </div>
       <div data-qa="shop-now-cta" class="cta-container bg-white pt6-sm pb7-sm pb5-lg prl12-sm pb8-sm 
        pt8-lg ta-sm-c xh-highlight">
          <div>
            <button class="cta-btn u-uppercase ncss-btn text-color-white ncss-brand d-sm-b d-lg-ib pr5- 
             sm pl5-sm pt3-sm pb3-sm d-sm-ib bg-black test-buyable buyable-full-width buyable-feed" 
             data-qa="notify-me-cta theme-feed">通知我
            </button>
          </div>
       </div>
     </div>
    </div>
</figcaption>

我想通过find_element_xpath找到该按钮,但它始终会显示

[<selenium.webdriver.remote.webelement.WebElement (session="10bf8a8d83d1b36188a6b1e41856c052", element="0.5294218443885808-2")>]

任何帮助将不胜感激。

    url = 'https://www.nike.com/cn/launch/'
browser = webdriver.Chrome()
browser.get(url)
elements = browser.find_element_by_xpath('//figure/div/div/figcaption/div/div/div[2]/div/button').text
print(elements)

1 个答案:

答案 0 :(得分:1)

单击按钮会引发WebDriverWait,然后等待element_to_be_clickable()并使用以下CSS选择器。

WebDriverWait(browser,10).until(EC.element_to_be_clickable((By.CSS_SELECTOR,'div[data-qa="shop-now-cta"] button[data-qa="notify-me-cta theme-feed"]'))).click()

您需要导入以下库。

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

已编辑

要获取按钮的文本,请使用以下代码。请使用get_attribute("textContent")get_attribute("innerHTML"),因为项目文本已隐藏在页面上。

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

browser=webdriver.Chrome()
browser.get("https://www.nike.com/cn/launch/")
print(WebDriverWait(browser,10).until(EC.presence_of_element_located((By.CSS_SELECTOR,'div[data-qa="shop-now-cta"] button[data-qa="notify-me-cta theme-feed"]'))).get_attribute("textContent"))