Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Selenium的Xpath嵌套括号问题(使用Python)_Python_Xpath_Selenium - Fatal编程技术网

Selenium的Xpath嵌套括号问题(使用Python)

Selenium的Xpath嵌套括号问题(使用Python),python,xpath,selenium,Python,Xpath,Selenium,我正在尝试使用Selenium和XPath获取一些数据 以下xpath工作正常: print sel.get_attribute("xpath=(//*[@id='course_list']/*[@class='series'])[4]//*[@class='series_links']//a/@href") 并返回4个匹配的URL。到目前为止还不错 问题是我想编写一个xpath来分别针对每个URL 使用Firefox xpath checker插件,我成功地确认以下代码完全符合我的需要: (

我正在尝试使用Selenium和XPath获取一些数据

以下xpath工作正常:

print sel.get_attribute("xpath=(//*[@id='course_list']/*[@class='series'])[4]//*[@class='series_links']//a/@href")
并返回4个匹配的URL。到目前为止还不错

问题是我想编写一个xpath来分别针对每个URL

使用Firefox xpath checker插件,我成功地确认以下代码完全符合我的需要:

((//*[@id='course_list']/*[@class='series'])[4]//*[@class='series_links']//a/@href)[1]
但是,尽管在FirefoxXPath检查器中工作,我似乎无法在Selenium中实现这一点

每当我尝试执行:

print sel.get_attribute("xpath=((//*[@id='course_list']/*[@class='series'])[4]//*[@class='series_links']//a/@href)[1]")
我得到以下错误:

Exception: ERROR: Invalid xpath [2]: ((//*[@id='course_list']/*[@class='series'])[4]//*[@class='series_links']//a
不知道这里发生了什么。我是犯了一个简单的错误,还是Selenium xpath不像FF xpath检查器那样支持嵌套括号


如果您有任何想法,我将不胜感激,因为我已经为此工作了数小时,但似乎无法使其工作:(

这并不是我问题的答案,但我确实为那些可能遇到类似问题的人找到了解决办法

Selenium的get_xpath_count命令允许进行相对轻松的xpath验证。如果指定了错误的xpath(或不存在的xpath),该命令将只返回零('0')

因此,我现在使用一个简单的“if”语句在运行get_attribute命令之前验证xpath是否存在:

if sel.get_xpath_count("(//*[@class='series_links'])[" + str(data) + "]//*[@class='youtube']") > 0:
    print sel.get_attribute("xpath=(//*[@id='course_list']/*[@class='series'])[" + str(data) +"]//*[@class='youtube']//a/@href")

同样,这不是对你问题的回答。但是,我从来没有像这样使用过XPath。如果网页作者足够聪明,可以使用类,那么他也足够聪明,可以更改网页的结构并保留这些类

from selenium import webdriver
driver = webdriver.Chrome() 

series = driver.find_element_by_class_name("series")
series_links = [i.get_attribute('href') for i in series.find_elements_by_class_name("series_links")]

driver.quit() # call this when you're done using the webdriver.

啊:(有没有关于如何用其他方法解决问题的想法?如果我运行print sel.get_属性(“xpath=(//*[@id='course\u list']]/*[@class='series']])[4]/*[@class='series\u links']///a/@href”)尽管xpath匹配了4个不同的URL,但它只打印一个结果。@MartijnPieters,不,这是一个语法和语义正确的xpath 1.0表达式。@DimitreNovatchev:好吧,那么猜错了。谢谢你的回答!我需要使用webdriver才能工作吗?目前我想我只是在使用RC('from selenium import selenium')。当我尝试运行您的代码时,我得到:'NameError:global name'driver'未定义'Yes,这是一个webdriver函数。我将编辑文章,以包含导入和其他内容,使其功能完整。