【问题标题】:How to extract text from div class using Selenium with Python如何使用 Selenium 和 Python 从 div 类中提取文本
【发布时间】:2026-02-06 23:50:01
【问题描述】:

我正在尝试创建一个机器人来自动支付一些账单。问题是我无法提取 div 类下的数量(文本)。错误是未找到元素。 使用了 driver.find_element_by_xpath 和 WebDriverWait。您能否指出如何获得突出显示的文本 - 请参阅附件链接?提前致谢。Page_inspect

【问题讨论】:

  • 这是我尝试过的:amount = WebDriverWait(self.driver, self.timeout).until( EC.presence_of_element_located((By.XPATH, '//*[@id="billPreferences"] /div/div[4]/div/div[2]/div[4]/div[3]/div/div/div/div/div[2]/div[1]/div[2]')) ) print('你的金额是:{}'.format(amount.text)) return float(amount.text)

标签: python selenium class webdriver


【解决方案1】:

我相信您的 xpath 存在一些问题。在下面尝试它应该可以工作:

amount = WebDriverWait(self.driver, self.timeout).until( EC.presence_of_element_located((By.XPATH, '//div[starts-with(@class,"bill-summary-total")]//div[contains(@data-ng-bind-html,"vm.productList.totalAmt")]'))) 
print('Your amount is: {}'.format(amount.text)) 
return float(amount.text) 

【讨论】:

  • Rahul,使用时您的代码出现此错误:selenium.common.exceptions.InvalidSelectorException:消息:无效选择器:无法使用 xpath 表达式定位元素 //div[starts-with(@class ,"bill-summary-total")//div[@data-ng-bind-html="vm.productList.totalAmt"] 因为以下错误: SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//div[starts-with(@class,"bill-summary-total")//div[@data-ng-bind-html="vm.productList.totalAmt"]' 不是有效的 XPath 表达式。
  • 是的,存在语法错误。因为忘记在 //div[starts-with(@class,"bill-summary-total")]//div[@data-ng-bind-html="vm.productList.totalAmt"] 中关闭 ] 。我已经更新了,请立即尝试。
  • 不幸的是,没有找到它:selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:{“method”:“xpath”,“selector”:“// div[starts-with(@class,"bill-summary-total")]//div[@data-ng-bind-html="vm.productList.totalAmt"]"}
  • 您是否可以分享您页面的链接,因为我不确定 xPath 中是否存在任何拼写错误。你也可以更新一个。
  • 无法分享链接,需要先登录后查看金额;附图中有完整的路径。
【解决方案2】:

你可以使用 -

driver.find_element_by_xpath("//div[@data-ng-bind-html='vm.productList.totalAmt']").text

我根据您所附的图片写了XPath。使用列表索引获取目标 div。例如-

driver.find_element_by_xpath("(//div[@data-ng-bind-html='vm.productList.totalAmt'])[1]").text

【讨论】:

  • @Pythonologist 不会将 driver.find_element_by_xpath()[1] 一起引发 TypeError 'WebElement' object is not subscriptable
  • @Swaroop- 使用您的代码时,得到这个:selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法找到元素:{“method”:“xpath”,“selector” :"(//div[@data-ng-bind-html='vm.productList.totalAmt'])[1]"}
  • 在查找元素之前使用time.sleep()wait()。它将确保该元素存在以供使用。看看,如果你的目标元素在iframe中,那么你必须先更改为iframe,然后再搜索该元素。
  • 你能帮我找到 iframe 并切换到正确的吗?我已经用过 WebDriverWait。