【发布时间】:2014-09-27 04:11:00
【问题描述】:
我使用 Python 和 selenium (PhantomJS webdriver) 来解析网站,但我遇到了问题。
我想从这个广播网站获取当前歌曲:http://www.eskago.pl/radio/eska-warszawa。
xpath:
/html/body/div[3]/div[1]/section[2]/div/div/div[2]/ul/li[2]/a[2]
xpath 不适用于 python selenium
错误:
Traceback(最近一次调用最后一次):文件“parser4.py”,第 41 行,在 p.loop() 文件“parser4.py”,第 37 行,循环中 self.eska(self.url_eskawarszawa) 文件“parser4.py”,第 27 行,在 eska driver.find_element_by_xpath('/html/body/div[3]/div[1]/section[2]/div/div/div[2]/ul/li[2]/a[2]') 文件 "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", 第 230 行,在 find_element_by_xpath 中 return self.find_element(by=By.XPATH, value=xpath) 文件“/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py”, 第 662 行,在 find_element 中 {'using': by, 'value': value})['value'] 文件“/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py”, 第 173 行,执行中 self.error_handler.check_response(response) 文件“/usr/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py”, 第 164 行,在 check_response 中 raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: 消息: u'{"errorMessage":"无法使用 xpath 找到元素 \'/html/body/div[3]/div[1]/section[2]/div/div/div[2]/ul/li[2]/a[2]\'","request": {"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"148","Content-Type": "application/json;charset=UTF-8","Host":"127.0.0.1:55583","User-Agent":"Python-urllib/2.7"},"httpVersion":"1.1","method" :"POST","post":"{\"使用\": \"xpath\"、\"sessionId\": \"e2fa7700-1bea-11e4-bd11-83e129ae286e\", \"值\": \"/html/body/div[3]/div[1]/section[2]/div/div/div[2]/ul/li[2]/a[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/e2fa7700-1bea-11e4-bd11 -83e129ae286e/元素"}}' ;屏幕截图:可通过屏幕获得
有人知道这有什么问题吗?
--------------------------------------
编辑: 谢谢大家的回答 我终于找到了解决我的问题的方法。 xpath 很好(但实际上很脆弱)
我使用 firefox 驱动程序,但我看到了问题 - 广告。
我将不得不跳过它们,我决定使用另一个没有此广告的页面: http://www.eskago.pl/radio
最后,谢谢 alecxe - 我用这个:
driver.find_element_by_xpath('//a[@class="radio-tab-button"]/span/strong').click()
element = driver.find_element_by_xpath('//p[@class="onAirStreamId_999"]/strong')
print element.text
完美运行。
【问题讨论】:
-
Unable to find element with xpath \'/html/body/div[3]/div[1]/section[2]/div/div/div[2]/ul/li[2]/a[2]\' -
你知道那条消息是什么意思吗?
-
您需要学习如何编写正确的 XPath。试试这个:zvon.org/xxl/XPathTutorial/General/examples.html
-
@Siking,你可能是对的,但如果没有更多的具体细节,很难遵循这种建议。您认为需要改进的 XPath 表达式有哪些方面?
-
@LarsH 很明显,OP 甚至不知道 XPath 是什么,更不用说如何构造一个了; OP还没有做最基本的研究。很抱歉,我还不够好,甚至无法用 600 个字符或更少的字符教别人 XPath 的基础知识,只能向他们指出我自己几年前开始的教程。
标签: python parsing selenium xpath selenium-webdriver