【问题标题】:selenium how to get the content of href within some targeted class硒如何在某些目标类中获取href的内容
【发布时间】:2013-11-08 23:08:18
【问题描述】:

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

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

我的目标是解析“#/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

但输出是

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

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

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

无论如何要得到那个?

【问题讨论】:

  • 为什么你没有得到实际的锚元素? anchorElement = target.find_element_by_tag_name('a') ...你可以这样做....print anchorElement.get_attribute("href")....对....?

标签: python html css xpath selenium


【解决方案1】:

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

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

【讨论】:

  • 如果没有你,我永远不会自己想出这个。非常感谢!
【解决方案2】:

这应该为你做:

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

【讨论】:

    【解决方案3】:

    如果您使用 find_element_by_id 或 classnamexpath 搜索特殊标签 然后使用 get_attribute('href')

    在这个例子中打印标签的所有属性

       ids = self.driver.find_elements_by_xpath('//*[@href]')
       for id in ids:
            print(id.get_attribute('href'))
           
    

    【讨论】:

      猜你喜欢
      • 2012-08-09
      • 2013-10-30
      • 2023-03-30
      • 2013-12-18
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-05
      相关资源
      最近更新 更多