Selenium - 找不到xpath的元素

Selenium - 找不到xpath的元素

问题描述:

我试图在this的页面上找到元素。特别是第一行中的竞标价格:196.20pSelenium - 找不到xpath的元素

我使用的硒,这是我的代码:

from selenium import webdriver 
driver = webdriver.PhantomJS() 
address = 'https://www.trustnet.com/factsheets/o/g6ia/ishares-global-property-securities-equity-index-uk' 
xpath = '//*[@id="factsheet-tabs"]/fund-tabs/div/div/fund-tab[3]/div/unit-details/div/div/unit-information/div/table[2]/tbody/tr[3]/td[2]' 
price = driver.find_element_by_xpath(asset['xpath']) 
print price.text 
driver.close() 

执行时我收到以下错误

NoSuchElementException: Message: {"errorMessage":"Unable to find element with xpath '//*[@id=\"factsheet-tabs\"]/fund-tabs/div/div/fund-tab[3]/div/unit-details/div/div/unit-information/div/table[2]/tbody/tr[3]/td[2]'","request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"214","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:62727","User-Agent":"Python http auth"},"httpVersion":"1.1","method":"POST","post":"{\"using\": \"xpath\", \"sessionId\": \"8faaff70-af12-11e7-a17c-416247c75eb6\", \"value\": \"//*[@id=\\\"factsheet-tabs\\\"]/fund-tabs/div/div/fund-tab[3]/div/unit-details/div/div/unit-information/div/table[2]/tbody/tr[3]/td[2]\"}","url":"/element","urlParsed":{"anchor":"","query":"","file":"element","directory":"/","path":"/element","relative":"/element","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/element","queryKey":{},"chunks":["element"]},"urlOriginal":"/session/8faaff70-af12-11e7-a17c-416247c75eb6/element"}} 
Screenshot: available via screen 

我用同样的方法,但使用不同的XPath,在yahoo finance和它工作正常,但不幸的是,我正在寻找的价格在那里不可用。

如果我不明白你的要求,那么这是你想刮的价格。我在这里使用了css选择器。

from selenium import webdriver 

driver = webdriver.Chrome() 
driver.get('https://www.trustnet.com/factsheets/o/g6ia/ishares-global-property-securities-equity-index-uk') 
price = driver.find_element_by_css_selector('[ng-if^="$ctrl.priceInformation.Mid"] td:nth-child(2)').text 
print(price.split(" ")[0]) 
driver.quit() 

结果:

196.20p/196.60p 

如果你想坚持的XPath那就试试这个:

price = driver.find_element_by_xpath('//*[contains(@ng-if,"$ctrl.priceInformation.Mid")]//td[2]').text 
+0

我已经接受了答案,因为它解决了原来的问题。一些评论虽然。 1.它似乎比xpath慢得多;这是正常的吗? 2.它不适用于PhantomJS。谢谢 – Rojj

+0

如果出现与速度有关的问题,它会有所不同。很少有人说css选择器比较好,因为它易于阅读和理解,而且很少推荐xpath,因为它能够以您期望的方式遍历Dom。但是,要明确您的想法,您可能需要查看http://elementalselenium.com/tips/32-xpath-vs-css此链接。 – SIM