这个错误信息...
selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: The result of the xpath expression "//a[following-sibling::input[@value="ST"]]/@href" is: [object Attr]. It should be an element.
......意味着你的XPath表达式无效xpath表达式.
您需要更换:
driver.find_element(By.XPATH, "//*[@id='topstuff']/div/div/p[1]/text()[2]")
with:
driver.find_elements(By.XPATH, "//*[@id='topstuff']/div/div/p[1]/text()")[2]
其他注意事项
Selenium https://stackoverflow.com/questions/54459701/what-is-selenium-and-what-is-webdriver/54482491#54482491 网络驱动程序 https://stackoverflow.com/questions/48079120/what-is-the-difference-between-chromedriver-and-webdriver-in-selenium/48080871#48080871支持xpath-1.0仅返回由xpath.
您可以找到xpath-1.0 /questions/tagged/xpath-1.0规格在XML 路径语言 (XPath) 版本 1.0 https://www.w3.org/TR/1999/REC-xpath-19991116/
但是,那xpath表达:
driver.find_elements(By.XPATH, "//*[@id='topstuff']/div/div/p[1]/text()")[2]
Is a xpath-2.0基于表达式,通常会返回一个object Text
。举几个例子:
-
//@version
:选择与上下文节点在同一文档中的所有版本属性节点
-
../@lang
:选择上下文节点父级的lang属性
您可以找到xpath-2.0 /questions/tagged/xpath-2.0规格在XML 路径语言 (XPath) 2.0(第二版) https://www.w3.org/TR/xpath20/
Solution
因此,您的代码块实际上将是:
if driver.find_elements(By.XPATH, "//*[@id='topstuff']/div/div/p[1]")[2]: