【问题标题】:Message: invalid selector: The result of the xpath expression is: [object Text]. It should be an element消息:无效选择器:xpath 表达式的结果是:[object Text]。它应该是一个元素
【发布时间】:2022-01-20 17:44:44
【问题描述】:

我试图在一个元素下分别打印 2 个文本文件,但因为我无法直接使用 selenium 选择文本文件(如第 1 个文本、第 2 个文本)

我想单独选择“主场胜利”“PSV vs Ajax”

我的代码:

driver.get("https://footystats.org/predictions/home-wins")

matches = driver.find_elements_by_xpath("//div[@class='predictionsList']//div[@class='betWrapper ']//div[@class='betHeaderTitle']/text()")
predictions = driver.find_elements_by_xpath("//div[@class='predictionsList']//div[@class='betWrapper ']//span[@class='market']")
odds = driver.find_elements_by_xpath("//div[@class='predictionsList']//div[@class='betWrapper ']//div[@class='betHeaderMeta']")

for x in range(0,len(matches)):
    print(matches[x].text, predictions[x].text, odds[x].text, sep="\t")

如果我这样编写代码,则会出错;

The result of the xpath expression is: [object Text]. It should be an element.

如果我从 'matches' 元素中删除 '/text()',它一次需要 2 个文本。

【问题讨论】:

    标签: python selenium xpath


    【解决方案1】:

    这个定位器

    //div[@class='predictionsList']//div[@class='betWrapper ']//div[@class='betHeaderTitle']
    

    会给你两个文本,而这一个

    //div[@class='predictionsList']//div[@class='betWrapper ']//div[@class='betHeaderTitle']/span[@class='market']
    

    只会给你“主场胜利”。
    因此,您可以获取总字符串并从中删除第一部分字符串以获得第二部分。
    因此,要仅获取第二个字符串,实际上是没有子元素文本的父元素文本,您可以执行以下操作:

    total_txt = driver.find_element_by_xpath("//div[@class='predictionsList']//div[@class='betWrapper ']//div[@class='betHeaderTitle']").text
    child_txt = driver.find_element_by_xpath("//div[@class='predictionsList']//div[@class='betWrapper ']//div[@class='betHeaderTitle']/span[@class='market']").text
    the_text_you_are_looking_for = total_txt.replace(child_txt, '')
    

    【讨论】:

    • 有没有办法获得“PSV vs Ajax”?
    • 当然,我会补充的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 2021-04-05
    • 2018-09-29
    • 2021-12-27
    • 2018-10-04
    • 1970-01-01
    相关资源
    最近更新 更多