如何使用selenium python以href值查找元素?

时间:2021-09-20 18:36:28

I have href value of an anchor tag which only have href value as attribute. Now I want to find the element in the page which have same value as my href value and click it. I am unable to find any way of doing this using standard selenium methods.How can I do this? Basically these are the functions I found but it seems that I can't use any of these:

我有一个只有href值作为属性的锚标记的href值。现在我想在页面中找到与href值具有相同值的元素并单击它。我无法使用标准的硒方法找到任何方法。我怎么能这样做?基本上这些是我发现的功能,但似乎我不能使用以下任何一个:

find_element_by_id
find_element_by_name
find_element_by_xpath
find_element_by_link_text
find_element_by_partial_link_text
find_element_by_tag_name
find_element_by_class_name
find_element_by_css_selector

3 个解决方案

#1


15  

You can use find_element_by_xpath functionality.

您可以使用find_element_by_xpath功能。

driver.find_element_by_xpath('//a[@href="'+variable+'"]');

#2


-1  

You would find the element by the CSS selector, as you would using vanilla CSS:

您可以通过CSS选择器找到该元素,就像使用vanilla CSS一样:

link = driver.find_element_by_css_selector('[href^=http://somelink.com/]')

You can also find the element by the link text:

您还可以通过链接文本找到该元素:

link = driver.find_element_by_partial_link_text('somelink')

#3


-1  

With Xpath you can localize HTML tags with attributes.

使用Xpath,您可以使用属性本地化HTML标记。

//a[@href='http://www.google.com']

The following should find it, tag a with attribute href with a specific value.

以下应该找到它,使用具有特定值的属性href标记a。

XPath tester: http://www.xpathtester.com/xpath/8ef1f4f708882bbecddc5161d18f6e1e

XPath测试器:http://www.xpathtester.com/xpath/8ef1f4f708882bbecddc5161d18f6e1e

#1


15  

You can use find_element_by_xpath functionality.

您可以使用find_element_by_xpath功能。

driver.find_element_by_xpath('//a[@href="'+variable+'"]');

#2


-1  

You would find the element by the CSS selector, as you would using vanilla CSS:

您可以通过CSS选择器找到该元素,就像使用vanilla CSS一样:

link = driver.find_element_by_css_selector('[href^=http://somelink.com/]')

You can also find the element by the link text:

您还可以通过链接文本找到该元素:

link = driver.find_element_by_partial_link_text('somelink')

#3


-1  

With Xpath you can localize HTML tags with attributes.

使用Xpath,您可以使用属性本地化HTML标记。

//a[@href='http://www.google.com']

The following should find it, tag a with attribute href with a specific value.

以下应该找到它,使用具有特定值的属性href标记a。

XPath tester: http://www.xpathtester.com/xpath/8ef1f4f708882bbecddc5161d18f6e1e

XPath测试器:http://www.xpathtester.com/xpath/8ef1f4f708882bbecddc5161d18f6e1e