使用xpath中的start with和ends函数查找selenium元素

2024-09-29 01:38:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图从这个enter link description here中提取类名符合regex模式frag-0-0、frag-1-0等的所有标记

我正在尝试以下代码

driver = webdriver.PhantomJS()
    for frg in frgs:
        driver.get(URL + frg[1:])
        frags=driver.find_elements_by_xpath("//*[starts-with(@id, 'frag-') and ends-with(@id, '-0')]")
    for frag in frags:
            for tag in frag.find_elements_by_css_selector('[class^=fragmark]'):
                lst.append([tag.get_attribute('class'), tag.text])
    driver.quit()

这是我的回溯:

Traceback (most recent call last): File "/home/ubuntu/workspace/vroniplag/vroni.py", line 116, in op('Aaf') File "/home/ubuntu/workspace/vroniplag/vroni.py", line 101, in op plags=getplags(cd) File "/home/ubuntu/workspace/vroniplag/vroni.py", line 92, in getplags frags=driver.find_elements_by_xpath("//[starts-with(@id, 'frag-') and ends-with(@id, '-0')]") File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 305, in find_elements_by_xpath return self.find_elements(by=By.XPATH, value=xpath) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 778, in find_elements 'value': value})['value'] File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute self.error_handler.check_response(response) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.InvalidSelectorException: Message: Error Message => 'Unable to locate an element with the xpath expression //[starts-with(@id, 'frag-') and ends-with(@id, '-0')] because of the following error: Error: INVALID_EXPRESSION_ERR: DOM XPath Exception 51' caused by Request => {"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"139","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:45340","User-Agent":"Python-urllib/2.7"},"httpVersion":"1.1","method":"POST","post":"{\"using\": \"xpath\", \"sessionId\": \"0dbc6ad0-4352-11e6-8cb8-4faebd646180\", \"value\": \"//*[starts-with(@id, 'frag-') and ends-with(@id, '-0')]\"}","url":"/elements","urlParsed":{"anchor":"","query":"","file":"elements","directory":"/","path":"/elements","relative":"/elements","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/elements","queryKey":{},"chunks":["elements"]},"urlOriginal":"/session/0dbc6ad0-4352-11e6-8cb8-4faebd646180/elements"} Screenshot: available via screen

我做错什么了?


Tags: inpyidbyvaluedriverseleniumwith
1条回答
网友
1楼 · 发布于 2024-09-29 01:38:14

你可以试着替换

"//*[starts-with(@id, 'frag-') and ends-with(@id, '-0')]"

"//*[starts-with(@id, 'frag-') and contains(@id, '-0')]"

因为Selenium不支持ends-with选项

相关问题 更多 >