在testerhome上发现一个问题,正好当时自己也遇到过,一直没解决,问题如下
li[8].find_element_by_css_selector("a.msk")
的输出 和li[8].find_element_by_xpath('//a[@class="msk"]')
的输出不同, 但是 xpath'//a[@class="msk"]'
转化成css就是a.msk
啊,求解.
# coding=utf-8
url='http://music.163.com/#/discover/playlist/?order=hot&cat=全部&limit=35&offset=0'
from selenium import webdriver
ff=webdriver.Firefox()
ff.get(url)
ff.switch_to_frame('g_iframe')
li=ff.find_elements_by_xpath('//div[@id="m-disc-pl-c"]/div//li')
print '*'*10
print li[8].find_element_by_css_selector("a.msk").get_attribute('title') # 结果是对的
print li[8]==li[0] # False
print li[8].find_element_by_xpath('//a[@class="msk"]').get_attribute("title") #结果错误的
print '*'*10
ff.quit()
之前我用java写的selenium,没去看源码,自己公司的项目在element下使用xpath寻找元素找的确实是全局的
今天正好用了python版的selenium,发现它的find_element_by_xpath有注释。。。
而且还很清晰。。。
def find_element_by_xpath(self, xpath):
"""Finds element by xpath.
:Args:
xpath - xpath of element to locate. "//input[@class='myelement']"
Note: The base path will be relative to this element's location.
This will select the first link under this element.
::
myelement.find_elements_by_xpath(".//a")
However, this will select the first link on the page.
::
myelement.find_elements_by_xpath("//a")
"""
return self.find_element(by=By.XPATH, value=xpath)
注释的意思就是要我们在element下使用相对路径来寻找元素。".//a"是元素下的所有链接,而去掉点的"//a"就是整个元素的所有链接了。 加上“.”,问题解决。真的是一个小数点引发的血案啊。