Python 按标签名称在元素中按标签名称查找元素(Selenium)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40022010/
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
Find element by tag name within element by tag name (Selenium)
提问by Jesse
I want to print all the href(links) from a website. All these hrefs are stored in an 'a' tag, and these a tags are stored in a 'li' tag. Now, I know how to select all the li's. I need a way to select all the a's within the li's to get the 'href' attribute. Tried the following but doesn't really work.
我想打印网站上的所有 href(链接)。所有这些 href 都存储在“a”标签中,而这些 a 标签则存储在“li”标签中。现在,我知道如何选择所有的 li。我需要一种方法来选择 li 中的所有 a 以获得“href”属性。尝试了以下但并没有真正起作用。
li = driver.find_elements_by_tag_name('li')
for link in li:
a_childrens = link.find_element_by_tag_name('a')
for a in a_children
(print a.get_attribute('href'))
Thanks in advance.
提前致谢。
回答by Buaban
I recommend css_selector instead of tag_name
我推荐 css_selector 而不是 tag_name
aTagsInLi = driver.find_elements_by_css_selector('li a')
for a in aTagsInLi:
(print a.get_attribute('href'))
回答by afonte
Try to select the links directly:
尝试直接选择链接:
links = driver.find_elements_by_tag_name('a')
回答by sytech
You have the right idea, but part of your problem is that a_childrens = link.find_element_by_tag_name('a')
will get you what you're looking for, but you're basically throwing out all of them because you get them in the loop, but don't do anything with them as you're in the loop. So you're only left with the variable from the last iteration.
你有正确的想法,但你的问题的一部分是这a_childrens = link.find_element_by_tag_name('a')
会让你得到你想要的东西,但你基本上把它们都扔掉了,因为你让它们进入循环,但不要对它们做任何事情你在循环中。所以你只剩下最后一次迭代的变量。
Your solution, correctly implemented, might look something like this
您的解决方案,正确实施,可能看起来像这样
list_items = driver.find_elements_by_tag_name("li")
for li in list_items:
anchor_tag = li.find_element_by_tag_name("a")
print(anchor_tag.get_attribute('href'))
That is, with the understanding that the HTML layout is as you described, something like:
也就是说,在理解 HTML 布局如您所描述的那样的情况下,例如:
<li><a href="foo">Hello</a></li>
<li><a href="bar">World!</a></li>
回答by Ahmed Saad
find_element_by_xpathwould do the trick...
find_element_by_xpath可以解决问题...
links = driver.find_elements_by_xpath('//li/a/@href')