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

ijnw1ujt  于 2022-12-25  发布在  Python
关注(0)|答案(4)|浏览(156)

我正试图从网页中检索数据有下面的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'的内容。
我真的不想做的是得到页面的源代码,然后做一个字符串搜索,这似乎是愚蠢的...。
去接电话吗

wb1gzix0

wb1gzix01#

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

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

bvjxkvbb2#

这应该可以帮到你:

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

dm7nw8vv3#

如果从find_element_by_id或类名xpath中搜索特殊标记,然后使用get_attribute(′ href ′)
在此示例中,打印标记所有属性

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

4ioopgfo4#

这应该可以做到:

div = driver.find_element(By.CLASS_NAME, 'abcxyz')
content = driver.find_element(By.LINK_TEXT,'Click_Me').get_attribute('href')
print(content)

使用 selenium 的Iam == 4.7.2

相关问题