31
votes

consider following HTML:

<div id='a'>
  <div>
    <a class='click'>abc</a>
  </div>
</div>

I want to click abc, but the wrapper div could change, so

driver.get_element_by_xpath("//div[@id='a']/div/a[@class='click']")

is not what I want

i tried:

 driver.get_element_by_xpath("//div[@id='a']").get_element_by_xpath(.//a[@class='click']")

but this would not work with deeper nesting

any ideas?

2
do you have to use xpath? cant you use a css selector? #a .click ? - Foo Bar User
Well change how? Does it gain an ID? Does it's position change? Does it place that a element into another element? - Arran
sry didnt understand your comment, the selector #a .click will get an element with id a and look inside for an element with class click. if the wrapper div changes it will still work. - Foo Bar User
driver.get_element_by_xpath("//a[@class='click']")? - Emanuele Bezzi
There is possibility for several <a class='click'>abc</a> elements in the page, so doesn't solve my case - user2534633

2 Answers

55
votes

HTML

<div id='a'>
  <div>
    <a class='click'>abc</a>
  </div>
</div>

You could use the XPATH as :

//div[@id='a']//a[@class='click']

output

<a class="click">abc</a>

That said your Python code should be as :

driver.find_element_by_xpath("//div[@id='a']//a[@class='click']")
-1
votes

Check this blog by Martin Thoma. I tested the below code on MacOS Mojave and it worked as specified.

> def get_browser():
>     """Get the browser (a "driver")."""
>     # find the path with 'which chromedriver'
>     path_to_chromedriver = ('/home/moose/GitHub/algorithms/scraping/'
>                             'venv/bin/chromedriver')
>     download_dir = "/home/moose/selenium-download/"
>     print("Is directory: {}".format(os.path.isdir(download_dir)))
> 
>     from selenium.webdriver.chrome.options import Options
>     chrome_options = Options()
>     chrome_options.add_experimental_option('prefs', {
>         "plugins.plugins_list": [{"enabled": False,
>                                   "name": "Chrome PDF Viewer"}],
>         "download": {
>             "prompt_for_download": False,
>             "default_directory": download_dir
>         }
>     })
> 
>     browser = webdriver.Chrome(path_to_chromedriver,
>                                chrome_options=chrome_options)
>     return browser