如何在 Selenium for Python 上使用 XPATH 语法选择元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19035186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to select element using XPATH syntax on Selenium for Python?
提问by user2534633
consider following HTML:
考虑以下 HTML:
<div id='a'>
<div>
<a class='click'>abc</a>
</div>
</div>
I want to click abc, but the wrapper div could change, so
我想点击 abc,但包装 div 可能会改变,所以
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?
有任何想法吗?
采纳答案by Arup Rakshit
HTML
HTML
<div id='a'>
<div>
<a class='click'>abc</a>
</div>
</div>
You could use the XPATHas :
您可以将XPATH用作:
//div[@id='a']//a[@class='click']
output
输出
<a class="click">abc</a>
That said your Python code should be as :
也就是说你的 Python 代码应该是:
driver.find_element_by_xpath("//div[@id='a']//a[@class='click']")
回答by Gayathry
Check this blog by Martin Thoma. I tested the below code on MacOS Mojave and it worked as specified.
查看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