32

考虑以下 HTML:

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

我想点击 abc,但包装 div 可能会改变,所以

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

不是我想要的

我试过了:

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

但这不适用于更深的嵌套

有任何想法吗?

4

2 回答 2

60

HTML

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

您可以将XPATH用作:

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

输出

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

也就是说,您的 Python 代码应为:

driver.find_element_by_xpath("//div[@id='a']//a[@class='click']")
于 2013-09-26T18:06:28.183 回答
-2

查看Martin Thoma的博客。我在 MacOS Mojave 上测试了以下代码,它按规定工作。

> 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
于 2019-10-21T20:19:23.870 回答