简体   繁体   English

使用 python 从 selenium 中的跨度括号中获取文本

[英]Get text from span bracket in selenium using python

I don't know if this is often asked but I just can't figure out how to get the text info of an span bracket in the html code using python with selenium.我不知道这是否经常被问到,但我只是不知道如何使用 python 和 selenium 在 html 代码中获取跨括号的文本信息。

For example following code:例如下面的代码:

<li class="addetailslist--detail">
area
<span class="addetailslist--detail--value">
72,05 m²
</span>
</li>

<li class="addetailslist--detail">
rooms
<span class="addetailslist--detail--value">
2,5
</span>
</li>

Since I have multiple elements of "addetailslist--detail" on the page, I want to address them by using the words "area" or "rooms".由于我在页面上有多个“addetailslist--detail”元素,我想通过使用“area”或“rooms”来解决它们。 Then I want to get the specific text from the class "addetailslist--detail--value" (eg 72,05m² and 2,5).然后我想从 class “addetailslist--detail--value”(例如 72,05m² 和 2,5)中获取特定文本。 I just can't figure out, how to address them the proper way.我只是不知道如何以正确的方式解决它们。 Can someone quickly help me on that one?有人可以快速帮助我吗?

This is how far I have come:这是我走了多远:

area = self.browser.find_element_by_xpath("//*[contains(text(), 'area')]")

But this just delievers the whole element...但这只是传递了整个元素......

To extract the texts eg 72,05 m² and 2,5 from all of the <span> using Selenium and you have to induce WebDriverWait for visibility_of_all_elements_located() and you can use either of the following Locator Strategies :要使用Selenium从所有<span>中提取文本,例如72,05 m²2,5 ,您必须为visibility_of_all_elements_located()引入WebDriverWait ,您可以使用以下任一定位器策略

  • Using CSS_SELECTOR and get_attribute("innerHTML") :使用CSS_SELECTORget_attribute("innerHTML")

     print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(self.browser, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "li.addetailslist--detail span.addetailslist--detail--value")))])
  • Using XPATH and text attribute:使用XPATH文本属性:

     print([my_elem.text for my_elem in WebDriverWait(self.browser, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//li[@class='addetailslist--detail']/span[@class='addetailslist--detail--value']")))])
  • Note : You have to add the following imports:注意:您必须添加以下导入:

     from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM