【问题标题】:How to extract the text $7.56 from the webpage using Selenium through Python如何通过 Python 使用 Selenium 从网页中提取文本 $7.56
【发布时间】:2020-01-20 21:36:12
【问题描述】:
  1. 转至:https://www.goodrx.com/amoxicillin
  2. 右键单击 $7.56(或任何价格)-> 在 chrome 开发工具中复制 xpath

我已经尝试了所有这些变化:

find_element(By.XPATH, '// *[ @ id = "uat-price-row-coupon-1"] / div[3] / div[1] / text()')  
find_element(By.XPATH, "//*[@id='uat-price-row-coupon-0']/div[3]/div[1]/text()")  
find_element_by_xpath("//*[@id='uat-price-row-coupon-1']/div[3]/div[1]/text()")  

我还验证了它可以在 Firefox 的“Try Xpath”中使用

但是我从硒中得到“没有这样的元素”。

我错过了什么吗?

【问题讨论】:

  • 您确定内容不是动态生成的吗?你写了“去”,但我从不听。

标签: python selenium xpath css-selectors webdriverwait


【解决方案1】:

要提取文本 $7.56,因为它是一个文本节点,您必须为 visibility_of_element_located() 诱导 WebDriverWait,您可以使用以下任一 Locator Strategies

  • 使用CSS_SELECTOR

    driver.get('https://www.goodrx.com/amoxicillin')
    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "ul[aria-label='List of best coupons by price and pharmacy.']>li div[data-qa='drug_price']")))
    print(driver.execute_script('return arguments[0].childNodes[1].textContent;', element).strip())
    
  • 使用XPATH

    driver.get('https://www.goodrx.com/amoxicillin')
    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//ul[@aria-label='List of best coupons by price and pharmacy.']/li//div[@data-qa='drug_price']")))
    print(driver.execute_script('return arguments[0].childNodes[1].textContent;', element).strip())
    
  • 控制台输出:

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

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

【讨论】:

  • 是的! execute_script('return arguments[0].childNodes[1] 是我一直在寻找的魔法。谢谢@DebanjanB
【解决方案2】:

使用WebDriverWait 等待元素可见性。该网站有机器人保护,准备好验证码。

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

# ...

wait = WebDriverWait(driver, 20)
with driver:
    driver.get("https://www.goodrx.com/amoxicillin")

    rows = wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, 'li[data-qa="price_row"]')))
    for row in rows:
        store_name = row.find_element_by_css_selector('[class^="goldAddUnderline"]').text.strip()
        drug_price = row.find_element_by_css_selector('[data-qa="drug_price"]').text.strip()
        drug_price = re.findall(r"\d+.\d+", drug_price)[0]
        print(store_name, drug_price)

【讨论】:

  • 是的....我确实尝试过这个...我试图避免正则表达式药品价格并直接获取文本
  • Xpath 和 text() 不能直接与 Selenium 一起工作。您可以使用 JS,其中一种方法是在 @DebanjanB 答案中。
猜你喜欢
  • 1970-01-01
  • 2021-12-05
  • 2017-12-04
  • 1970-01-01
  • 2019-10-19
  • 1970-01-01
  • 2019-07-10
  • 2020-02-15
  • 1970-01-01
相关资源
最近更新 更多