Python selenium 如何在某个目标类中获取href 的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19664253/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:17:28  来源:igfitidea点击:

selenium how to get the content of href within some targeted class

pythonhtmlcssxpathselenium

提问by runcode

I am trying to retrieve the data from the webpage has the html in below

我正在尝试从网页中检索数据,其中 html 在下面

       <div class="someclass">
       <p class="name"><a href="#/word/1/">helloworld</a></p>
       </div>

My goal is to parse "#/word/1/" What I did is

我的目标是解析“#/word/1/”我所做的是

        target = self.driver.find_element_by_class_name('someclass')
        print target
        print target.text
        print target.get_attribute("css=a@href")
        print target.tag_name

but the output are

但输出是

 <selenium.webdriver.remote.webelement.WebElement object at 0x10bf16210>
 helloworld
 None
 div 

I tried so many ways , it seems there is no way i can get the content of 'a href' within the targeted class.

我尝试了很多方法,似乎无法在目标类中获得“a href”的内容。

I really dont want to do is get the source code of the page, and then do a string searching, that seems dumb....

我真的不想做的是获取页面的源代码,然后进行字符串搜索,这似乎很愚蠢....

anyway to get that?

无论如何要得到那个?

采纳答案by aychedee

As far as I am aware you can get the href by searching through the child elements

据我所知,您可以通过搜索子元素来获取 href

div = self.driver.find_element_by_class_name('someclass')
div.find_element_by_css_selector('a').get_attribute('href')

回答by Andrew

This should do it for you:

这应该为你做:

self.driver.find_element_by_css_selector('.someclass a').get_attribute('href')