【问题标题】:How to locate an element and extract required text with Selenium and Python如何使用 Selenium 和 Python 定位元素并提取所需文本
【发布时间】:2019-09-06 23:08:46
【问题描述】:

我正在使用 Selenium 在网页上输入数据,但其中一个输入字段出现问题。这是导致我遇到困难的 HTML 代码:

<div class="form-group">
<label for="address">Enter your address</label>
<input type="text" name="address" class="form-control" value="" style="font-size:1.8em;padding:15px;height:40px">
<label for="address">Enter this code: 2784873 </label>
<input type="text" name="code" class="form-control" value="" style="font-size:1.8em;padding:15px;height:40px">

我想使用 Selenium 复制 Enter this code: 2784873 之后的数值(在本例中为 2784873),然后我会在下面的输入字段中输入该数值,但目前无法弄清楚如何得到这个。我尝试使用driver.find_element_by_id(),但没有成功。我还尝试使用 xpath(在我看来这是最好的方法):

codes = driver.find_elements(By.XPATH, "//*[@id=\"page-wrapper\"]/div[2]/div[2]/center/form/div/label[2]")

但是codes中返回的值是:

<selenium.webdriver.remote.webelement.WebElement (session="ae4e91d8ec7e2bc161", element="0.570523580858733-2")

谁能建议一种方法来做到这一点?

【问题讨论】:

  • codes.getText() 的值是多少?
  • 不确定你打算在哪里使用它。如果我这样做 print(codes.getText() 我会收到一个错误:'WebElement' object has no attribute 'getText'
  • 谢谢你的线索,想通了!

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


【解决方案1】:

感谢上面glhr 提供的线索,我能够弄清楚这一点。 glhr 询问 codes.getText() 透露了什么,但 getText() 是针对 Java 版本的 Selenium。在这种情况下,我使用的是 Python,所以应该是 .text:

codes = driver.find_elements(By.XPATH, "//*[@id=\"page-wrapper\"]/div[2]/div[2]/center/form/div/label[2]").text

对于上面的示例返回“输入此代码:2784873”。

问题已解决,谢谢!

编辑:也感谢QHarr,在我写这篇文章的时候,他的解决方案就出现了。

【讨论】:

  • 您的代码无法运行,因为您使用的是find_elements(复数),这将引发错误。此外,您的定位器对于所有级别和索引都非常脆弱。您应该接受(并使用)QHarr 的回答。定位器不那么脆弱并且代码有效。
  • 谢谢,find_elements 是一个错字,实际上我最终使用了find_element。但是,我接受并正在使用 QHarr 的回答。谢谢!
【解决方案2】:

你可以使用

driver.find_element_by_css_selector('.form-control + [for=address]').text

如果需要,使用replace() 删除enter this code: 字符串

那是一个类选择器“。”将相邻的兄弟组合器连接到属性 = 值选择器。所以属性为for 的元素的值是address,它与类form-control 的元素相邻。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    相关资源
    最近更新 更多