【问题标题】:How to extract the text 5 from the text node within the parent div node using Selenium and Python如何使用 Selenium 和 Python 从父 div 节点内的文本节点中提取文本 5
【发布时间】:2021-03-05 12:29:17
【问题描述】:

我正在尝试从<div> 中提取文本,这是带有 XPath

的内部双引号(请参阅屏幕截图)
<div class="two columns" style="font-size: 18px; padding-top: 5px;">
  <img src="images/spins_s.png" border="0" style="margin-bottom: -1px;"> 
   5
</div>

我在这里附上截图, [ https://i.stack.imgur.com/uOmeS.png][1] 当我在 cole 中尝试这个 xpath 表达式时,它的返回 正确的 o/p,

>>$x("//div[@class='two columns']/img[@src='images/spins_s.png']/..")[0].innerText
>>" 5"

但是当我要在python中运行这个代码

spin_balance = browser.find_element_by_xpath("//div[@class='two columns']/img[@src='images/spins_s.png']/..")[0].innerText

它给出了这样的错误

spin_balance = browser.find_element_by_xpath("//div[@class='two columns']/img[@src='images/spins_s.png']/..")[0].innerText
TypeError: 'WebElement' object is not subscriptable

HTML 图像:

【问题讨论】:

    标签: python-3.x selenium xpath css-selectors webdriverwait


    【解决方案1】:

    文本 5 位于文本节点内。因此,要打印文本,您必须为visibility_of_element_located() 诱导WebDriverWait,您可以使用以下任一Locator Strategies:

    • 使用CSS_SELECTOR和text属性:

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.two.columns"))).text)
      
    • 使用XPATH和text属性:

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='two columns']"))).text)
      
    • 使用XPATH 和childNodes:

      print(driver.execute_script('return arguments[0].lastChild.textContent;', WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='two columns'][./img[@src='images/spins_s.png']]")))).strip())
      
    • 使用XPATH 和splitlines():

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='two columns'][./img[@src='images/spins_s.png']]"))).get_attribute("innerHTML").splitlines()[2])
      
    • 注意:您必须添加以下导入:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 2019-09-03
      • 2018-11-15
      相关资源
      最近更新 更多