我正在嘗試分別在一個元素下列印 2 個文本檔案,但是因為我無法直接使用 selenium 選擇文本檔案(例如第一個文本,第二個文本)
![訊息:無效選擇器:xpath 運算式的結果是:[object Text]。它應該是一個元素](https://img.uj5u.com/2022/01/22/9ab0eaa91c8b43b5bd5b7cde4f95cf0c.png)
我想單獨選擇“主場勝利”“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 個文本。
uj5u.com熱心網友回復:
這個定位器
//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, '')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/417979.html
標籤:
