使用文本硒beautifulsoup python获取标签

时间:2019-09-14 07:53:37

标签: python selenium selenium-webdriver beautifulsoup

我知道有一种使用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 中有没有办法获得标签,使用文本进行搜索?

2 个答案:

答案 0 :(得分:1)

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

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

将所有内容放在一起:

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

演示:

enter image description here

更多信息:XPath Operators & Functions

答案 1 :(得分:0)

在Selenium中,您可以尝试进行Sub string匹配。

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