在 HTML 文本中查找元素 - Selenium Python

问题描述 投票:0回答:2

我正在尝试通过纯文本或

innerHTML
文本查找元素:

newresults = driver.find_elements("xpath","//*[@class='card is-category-product']")    
for result in newresults:
    htmlEl = result.get_attribute('innerHTML')

所以基本上我想在我的 htmlEl 变量中搜索

htmlEl
按如下方式返回每个块:

<figure class="card-figure card-link">
    <picture class="card-picture ratio ratio-4x3">
        <source srcset="url-to-image">
        <source srcset="url-to-image"> <img src="url-to-image" class="card-img object-fit-contain is-contain" loading="lazy" alt="image-alt"> </picture>
    <figcaption class="card-caption">
        <h3 class="mb-0">TITLE OF CARD</h3>
        <p class="small">Random text</p>
    </figcaption>
    <a href="/random-url" class="card-link-overlay" title="TITLE" aria-label="title"></a>
</figure>

例如,我想找到类为“mb-0”的 H3 元素,该元素应该返回 - TITLE OF CARD。我试过了

foundname = driver.find_element(By.XPATH, "//h3[@class='mb-0']")

但显然这会在我指定的原始 URL 中搜索,而不是在我的

htmlEl
变量中搜索。

python selenium-webdriver
2个回答
0
投票

您可以迭代结果并在每个结果中进行搜索。

newresults = driver.find_elements("xpath","//*[@class='card is-category-product']")

for result in newresults:
    h3_tag = result.find_element(By.XPATH, "//h3[@class='mb-0']")
    print(h3_tag.text)

0
投票

您不想搜索元素的“innerHTML”,因为这会将实际的 HTML 作为文本返回,就像页面 DOM 中一样。这意味着您需要解析 HTML 等。Selenium 可以更轻松地处理这种情况。

您需要的是链接

.find_element()
调用,例如

newresults = driver.find_elements(By.XPATH, "//*[@class='card is-category-product']")    
for result in newresults:
    htmlEl = result.find_element(By.XPATH, ".//h3[@class='mb-0']")
             ^^^^^^ we start from result

因为我们正在链接 .find_element() 调用并使用 XPath,所以您需要添加一个 .find_element() 。 (点)位于内部 XPath 的开头

.//h3[@class='mb-0']
^ add a dot here

表示您要从元素“结果”开始搜索。

注意:如果您使用任何其他定位器类型,例如CSS选择器、ID等不需要添加这个点。例如,使用 CSS 选择器的相同代码将是

newresults = driver.find_elements(By.CSS_SELECTOR, ".card.is-category-product")    
for result in newresults:
    htmlEl = result.find_element(By.CSS_SELECTOR, "h3.mb-0")

出于很多原因,我更喜欢 CSS 选择器而不是 XPath...

  1. 他们更快
  2. 他们有更好的浏览器支持
  3. 语法更短、更简单、更易于阅读
© www.soinside.com 2019 - 2024. All rights reserved.