如何使用Python中的Selenium选择元素并获取文本?

huangapple go评论72阅读模式
英文:

How to select element with selenium in python and get the text?

问题

在Python中,我正在尝试选择此元素并提取文本。我尝试使用以下表达式:

element = browser.find_element(By.XPATH, "//button[@stid='FLIGHTS_DETAILS_AND_FARES-index-1-LDUWT-FlightsActionButton']")
print(element.text)

我还尝试了以下表达式:

element = browser.find_element(By.XPATH, "//button[contains(text(), 'Select and show fare information')]")
print(element.text)

请注意,stid 元素可能会在对网页的多次调用之间更改。

英文:

In python I am trying to select this element

<button stid="FLIGHTS_DETAILS_AND_FARES-index-1-LDUWT-FlightsActionButton" data-test-id="select-link" data-stid="FLIGHTS_DETAILS_AND_FARES-index-1-LDUWT-FlightsActionButton" class="uitk-card-link" type="button"><span class="is-visually-hidden">Select and show fare information for Etihad Airways flight, departing at 10:50am from Geneva, arriving at 1:05pm in Tokyo, Priced at $2,224 Roundtrip per traveler. Arrives 1 day later. 19 hours 15 minutes total travel time, One stop, Layover for 3 hours 10 minutes in Abu Dhabi.</span></button>

and to extract the text. I tried to use the following expression

element = browser.find_element(By.XPATH, "//button[@stid='FLIGHTS_DETAILS_AND_FARES-index-1-LDUWT-FlightsActionButton']")
print(element.text)

I also tried

element = browser.find_element(By.XPATH, '//button[contains(text(), "Select and show fare information")]')
print(element.text)

which results in an "Unable to locate element" error.

Also the stid element might change between calls to the webpage.

答案1

得分: 2

你的定位器不正确,我已经更正了你上面提供的两个。尝试以下任何一个,并提取 span 元素的文本。

#1 由于 ID 的一部分是动态的,你可以使用 contains

//button[contains(@stid,'FLIGHTS_DETAILS_AND_FARES')]//span

#2 文本元素的标签实际上是 span 而不是 button

//span[contains(text(), "选择并显示票价信息")]

英文:

your locators were not correct, i ahve corrected both you have provided above
try any of these below and Extract the text for the span element

#1 Since part of ID is dynamic you can just use contains

//button[contains(@stid,'FLIGHTS_DETAILS_AND_FARES')]//span

#2 The text element Tag is actually span not button

//span[contains(text(), "Select and show fare information")]

huangapple
  • 本文由 发表于 2023年5月13日 15:13:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76241511.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定