[英]Python Selenium: Click a href=“javascript:()”
I am using chromedriver and I have the following webpage source: 我正在使用chromedriver,并且具有以下网页资源:
<form id="stepLinksForm" name="stepLinksForm" method="POST" target="mainFrame">
<ul>
<li> <a href="javascript:submitLink('action_one.htm')">Action One</a> </li>
<li> <a href="javascript:submitLink('action_two.htm')">Action Two</a> </li>
<li> <a href="javascript:submitLink('action_three.htm')">Action Three</a> </li>
</ul>
</form>
After clicking anyone of the href, the browser goes to a new page but the url stays the same. 单击href中的任何一个后,浏览器将转到新页面,但URL保持不变。 What I want to achieve is clicking the first href, ie
<li> <a href="javascript:submitLink('action_one.htm')">Action One</a> </li>
我想要实现的是单击第一个href,即
<li> <a href="javascript:submitLink('action_one.htm')">Action One</a> </li>
I have tried find_element_by_xpath, link_text and some other methods suggested on the Internet but none of them works. 我已经尝试过在互联网上建议使用find_element_by_xpath,link_text和其他一些方法,但是它们都不起作用。 I really appreciate if someone could help.
我真的很感谢有人能帮上忙。
To click on the first href with text as Action One you can use either of the following options ( Python Language Binding Art ) : 要单击第一个具有文本作为Action One的 href,可以使用以下选项之一( Python语言绑定图 ):
linkText
: linkText
:
driver.find_element_by_link_text("Action One").click()
cssSelector
: cssSelector
:
driver.find_element_by_css_selector("a[href*='action_one.htm']").click()
xpath
: xpath
:
driver.find_element_by_xpath("//a[contains(@href,'action_one.htm') and contains(.,'Action One')]").click()
As you are unable to locate the element through LINK_TEXT
, CSS
, XPATH
and even after time.sleep()
it is pretty much confirmed that the element is within an frame which is denoted by the <frame>
tag. 如你无法找到通过该元件
LINK_TEXT
, CSS
, XPATH
和甚至之后time.sleep()
它是相当多确认元件是由表示的帧内 <frame>
标记。
Now as you are able to see them by "Inspect" , locate the element within the HTML DOM and traverse up the HTML . 现在, 通过“检查”可以看到它们,在HTML DOM中找到该元素,然后遍历HTML 。 At some point you will find a
<frame>
tag. 在某个时候,您会找到一个
<frame>
标签。 Grab the attributes of the <frame>
tag and switch to the intended frame first and then try to use the Locator Strategies provided in my answer. 抓住
<frame>
标记的属性,然后首先切换到预期的帧 ,然后尝试使用我的答案中提供的“ 定位器策略” 。 Here you can find a detailed discussion on How can I select a html element no matter what frame it is in in selenium? 在这里,您可以找到有关如何选择一个html元素的详细讨论, 无论它处于硒的哪个帧中?
Instead of click you can call the javascript code directly: 不用单击即可直接调用javascript代码:
browser.execute_script("submitLink('action_one.htm')")
which equivalent to javascript:submitLink('action_one.htm') 相当于javascript:submitLink('action_one.htm')
Or you can find the a by its text: 或者,您可以通过其文本找到a:
browser.find_elements_by_xpath("//a[contains(text(), 'Action One')]")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.