【问题标题】:Get tag using text selenium beautifulsoup python使用文本 selenium beautifulsoup python 获取标签
【发布时间】:2020-01-15 21:57:57
【问题描述】:

我知道有一种方法可以使用 xpath 和 javascript

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

但是这种方法不检测元素/标签,它们被定义为标签,例如:

    <p>
      <span class="text-primary">UK</span>
      +44 (0) 1865 987 667<br>
      Piccadilly Gardens, 49 Piccadilly, Manchester, M1 2AP </p>

在这种情况下,如果文本是+44 (0) 1865 987,它不会得到元素。

  1. 此问题在许多示例中重复出现,以这种方式合并文本。可能是什么原因?
  2. 有没有办法在beautifulsoup中获取标签,使用文本搜索?

【问题讨论】:

  • html 中可以出现不止一次吗?
  • @QHarr 是的。可以有。我通过使用 selenium 搜索所有标签,然后与调用字符串匹配找到了解决方案。我为标签添加了 ap。但是,它可以比这更通用。

标签: python selenium selenium-webdriver beautifulsoup


【解决方案1】:

我的期望是您需要使用以下功能组合:

  1. normalize-space() - 在子项中查找匹配项/忽略前导/尾随空格等。
  2. contains() - 部分匹配

把所有东西放在一起:

element = driver.find_element_by_xpath("//*[contains(normalize-space(),'+44 (0) 1865 987 667')]")

演示:

更多信息:XPath Operators & Functions

【讨论】:

    【解决方案2】:

    在 Selenium 中,您可以尝试使用 Sub string 匹配。

    text="+44 (0) 1865 987 667"
    print(WebDriverWait(driver,20).until(EC.visibility_of_element_located((By.XPATH,"//*[contains(.,'" + text + "')]"))).text)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-22
      • 2016-03-26
      • 1970-01-01
      • 2022-11-10
      • 2015-08-29
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      相关资源
      最近更新 更多