-3

I am using Selenium to enter data on a web page, but have run into an issue with one of the input fields. This is the HTML code causing my difficulty:

<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">

I want to use Selenium to copy the numeric value after Enter this code: 2784873 (in this case, 2784873), which I would then enter in the input field below, but so far have been unable to figure out how to get this. I tried using driver.find_element_by_id() but that was unsuccessful. I also tried using xpath (which seems to me like the best approach) with:

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

but the value returned in codes is:

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

Can anyone suggest a way to do this?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
pioniere
  • 124
  • 1
  • 8

2 Answers2

3

You can use

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

Use replace() to remove the enter this code: string if required

That is a class selector "." with adjacent sibling combinator joining to attribute = value selector. So element with attribute for having value address that is adjacent to element with class form-control.

QHarr
  • 83,427
  • 12
  • 54
  • 101
-1

Thanks to the clue offered by glhr above, I was able to figure this out. glhr asked what codes.getText() revealed, but getText() is for the Java version of Selenium. In this case I am using Python, so it should be .text:

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

which for the example above returns "Enter this code: 2784873".

Problem solved, thanks!

Edit: Thanks to QHarr as well, whose solution came in just as I was writing this.

JeffC
  • 22,180
  • 5
  • 32
  • 55
pioniere
  • 124
  • 1
  • 8
  • 2
    Your code is NOT going to work because you are using `find_elements` (plural) which will throw an error. Also your locator is very brittle with all the levels and indices. You should accept (and use) QHarr's answer. The locator is much less brittle and the code works. – JeffC Apr 16 '19 at 21:46
  • Thanks, the `find_elements` was a typo, I actually ended up using `find_element`. However, point taken, I accepted and am using QHarr's answer. Thanks! – pioniere Apr 16 '19 at 22:04