Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Python/Selenium-Can';t获取标记的HREF值_Java_Python_Selenium_Selenium Chromedriver - Fatal编程技术网

Java Python/Selenium-Can';t获取标记的HREF值

Java Python/Selenium-Can';t获取标记的HREF值,java,python,selenium,selenium-chromedriver,Java,Python,Selenium,Selenium Chromedriver,我有一个HTML元素: <h2 class="post-title"> <a href="http://google.com" rel="bookmark">This a link to Google!</a> </h2> 我正在使用driver.find\u elements\u by\u class\u name('post-title')来查找这段HTML 但如何仅提取“href”标记的值? 我试过: driver.get_

我有一个HTML元素:

<h2 class="post-title">

    <a href="http://google.com" rel="bookmark">This a link to Google!</a>

</h2>

我正在使用
driver.find\u elements\u by\u class\u name('post-title')
来查找这段HTML

但如何仅提取“href”标记的值?

我试过:

driver.get_属性('href')

返回“无”


谢谢

事实上,标记为
h2的兄弟姐妹没有href属性,这是您通过搜索元素
(通过类名称(“post-title”)
找到的。是兄弟姐妹
起作用

用xpath搜索怎么样?如果
'post-title'
是唯一的类标识符,则可以按如下方式搜索元素

xpth = "//*[@class='post-title']/a"
a_element = driver.find_element_by_xpath(xpth)
最后

href = a_element.get_attribute('href')

从你(几乎)拥有的东西中你可以做些什么

您有两个问题:

  • 您正在尝试查找
    h2
    元素,而不是
    a
  • 您正在尝试从
    WebDriver
    实例获取属性值
尝试以下代码以获得所需的输出:

driver.find_element_by_css_selector('h2.post-title>a').get_attribute('href')

href
属于
标签;因此,首先必须达到以下元素:

elem = driver.find_element_by_xpath('//h2[@class="post-title"]/a')

attribute_value = elem.get_attribute('href')

事实上,标记为
h2
的兄弟姐妹没有href属性,这是您通过搜索元素
“class\u name”(“post-title”)
的目标。问题是,如果我试图在网页中找到所有的链接,我会得到90多个链接,其中只有10个是我感兴趣的。如何从这段HTML中提取数据?如果Andersson的答案符合您的需要,请选择正确的答案。
elem = driver.find_element_by_xpath('//h2[@class="post-title"]/a')

attribute_value = elem.get_attribute('href')