所以我有这个HTML元素:
<h2 class="post-title">
<a href="http://google.com" rel="bookmark">This a link to Google!</a>
</h2>
我正在使用driver.find_elements_by_class_name('post-title')
来查找这段HTML。
但是我怎样才能只提取&#34; href&#34;标记吗
我试过了:
driver.get_attribute(&#39; HREF&#39)
返回&#39;没有&#39;
由于
答案 0 :(得分:1)
确实标签为function parseData(data = Data) {
的兄弟没有href属性,而这是您通过搜索元素function parseData(data: Data) {
定位的属性。这是兄弟h2
。
用xpath搜索怎么样?如果by_class_name('post-title')
是唯一的类标识符,则可以按如下方式搜索元素
<a></a>
最后
'post-title'
<小时/> 你可以做什么(你几乎)
xpth = "//*[@class='post-title']/a"
a_element = driver.find_element_by_xpath(xpth)
答案 1 :(得分:1)
你有两个问题:
h2
元素,而不是a
WebDriver
实例尝试使用以下代码获取所需的输出:
driver.find_element_by_css_selector('h2.post-title>a').get_attribute('href')
答案 2 :(得分:0)
href
属于<a>
标记;所以首先你必须达到以下要素:
elem = driver.find_element_by_xpath('//h2[@class="post-title"]/a')
attribute_value = elem.get_attribute('href')