且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Selenium Python在html的span数据绑定部分中获取文本?

更新时间:2022-03-14 23:00:28

要打印文本 添加到购物袋,您可以使用以下

To print the text Add to bag you can use either of the following Locator Strategies:

  • 使用 css_selector get_attribute("innerHTML"):

print(driver.find_element_by_css_selector("button[data-test-id='add-button'][aria-label='Add to bag'] span").get_attribute("innerHTML"))

  • 使用 xpath text 属性:

    print(driver.find_element_by_xpath("//button[@data-test-id='add-button' and @aria-label='Add to bag']//span").text)
    

  • 理想情况下,您需要为引入 WebDriverWait visible_of_element_located(),您可以使用以下任一定位器策略:

    Ideally you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

    • 使用 CSS_SELECTOR text 属性:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "button[data-test-id='add-button'][aria-label='Add to bag'] span"))).text)
    

  • 使用 XPATH get_attribute():

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//button[@data-test-id='add-button' and @aria-label='Add to bag']//span"))).get_attribute("innerHTML"))
    

  • 注意:您必须添加以下导入:

  • Note : You have to add the following imports :

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