如何通过子标签中的文本查找标签

时间:2020-02-09 10:28:27

标签: python html selenium

我是Webelement和selenium的新手,任何人都可以使用文本“ Hotel Wahington”帮助我如何在下面找到元素:

<a class="hotel_name_link url" href="/hotel/nl/washington.html?label=gen173nr-1FCAEoggI46AdIM1gEaFCIAQGYATG4ARjIAQzYAQHoAQH4AQKIAgGoAgS4Apyz__EFwAIB&amp;sid=1b691d9ad57ac7ee7c3d40dac2f7f488&amp;dest_id=-2140479&amp;dest_type=city&amp;group_adults=2&amp;group_children=0&amp;hapos=1&amp;hpos=1&amp;no_rooms=1&amp;sr_order=popularity&amp;srepoch=1581242789&amp;srpvid=87de4712b9a90095&amp;ucfs=1&amp;from=searchresults;highlight_room=#hotelTmpl" target="_blank" rel="noopener">
  <span class="sr-hotel__name" data-et-click="    ">Hotel Washington</span>
  <span class="invisible_spoken">Opens in new window</span>
</a>

在下面添加原始链接: https://www.booking.com/searchresults.html?label=gen173nr-1FCAEoggI46AdIM1gEaFCIAQGYATG4ARjIAQzYAQHoAQH4AQKIAgGoAgS4ApSSgPIFwAIB&sid=dcd3ff4c30abfd0bc264d5ae4a4c1d7a&sb=1&sb_lp=1&src=index&src_elem=sb&error_url=https%3A%2F%2Fwww.booking.com%2Findex.html%3Flabel%3Dgen173nr-1FCAEoggI46AdIM1gEaFCIAQGYATG4ARjIAQzYAQHoAQH4AQKIAgGoAgS4ApSSgPIFwAIB%3Bsid%3Ddcd3ff4c30abfd0bc264d5ae4a4c1d7a%3Bsb_price_type%3Dtotal%26%3B&sr_autoscroll=1&ss=hotel+washington&is_ski_area=0&checkin_year=&checkin_month=&checkout_year=&checkout_month=&group_adults=2&group_children=0&no_rooms=1&b_h4u_keep_filters=&from_sf=1

5 个答案:

答案 0 :(得分:1)

要基于text "Hotel Wahington"选择锚标记,请使用以下xpath。

使用以下Xpath

driver.find_element_by_xpath("//a[@class='hotel_name_link url' and contains(.,'Hotel Washington')]").click()

或跟随css选择器。

driver.find_element_by_css_selector("a.hotel_name_link.url[href*='/hotel/nl/washington']").click()

或部分链接文本。

driver.find_element_by_partial_link_text("Hotel Washington").click()

答案 1 :(得分:0)

使用xpath可以通过..转到父元素

driver.find_element_by_xpath('//span[.="Hotel Washington"]/..')

或找到具有特定文本的元素

driver.find_element_by_xpath('//a[span[.="Hotel Washington"]]')

答案 2 :(得分:0)

使用

xPath = //*[contains(@text(),'Hotel Wahington')]

OR

//a[@class='hotel_name_link url']//*[contains(@text(),'Hotel Wahington')]

答案 3 :(得分:0)

试用此xpath: // span [text()='Hotel Washington'] / parent :: a

还要注意,答案中的方法“ find_element_by_xpath()”来自Selenium的版本4,该版本仍处于Alpha测试阶段。您很可能会使用Selenium版本3。版本3的有效代码为:

driver.findElement(By.xpath("//span[text()='Hotel Washington']/parent::a")),click();

答案 4 :(得分:0)

您只能使用text来查找元素。您可以尝试以下解决方案:

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

element = WebDriverWait(driver, 50).until(
    EC.presence_of_element_located((By.XPATH, "//span[contains(., 'Hotel Washington')]")))
element.click()