Selenium / python-“查找部分链接文本”和“ xpath”

我是Selenium包的新手。尝试确定网站上是否存在给定文本时,我遇到了2个问题。 网站地址:

www.kbc.com 

我需要在他们的菜单栏上显示文本“投资者关系”。但是不断失败。请帮我检查一下。谢谢。

您还可以在这里找到部分元素:

<div class="nav--main__item-wrapper">
<a href="/en/investor-relations.html?zone=topnav">
Investor Relations
</a>
<div class="nav--main__dropdown js-toggle" data-target="menu-item--383357923" data-slide-speed="200">
<svg xmlns="http://www.w3.org/2000/svg" width="10.607" height="10.606" viewBox="0 0 10.607 10.606">
<path d="M10.24,5.11,6,9.35,1.76,5.11"></path>
</svg>
</div>
</div>

安装的软件包:

import requests
import pandas
import time
import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import select
from selenium.webdriver.support.select import Select
from selenium.webdriver.support import expected_conditions as EC
import os
import io
import random
from pathlib import Path

chromedriver = "/Users/xxx/xxx/chromedriver"
browser = webdriver.Chrome(chromedriver)

Xpath:/ html / body / header / div [2] / div / div [2] / nav / ul / li [3] / div [1] / a

browser.get("https://www.kbc.com/en.html")
browser.implicitly_wait(30) 
# Locating Hyperlinks by Link Text
invest_link = browser.find_elements_by_xpath('//a[contains(@href, "Investor Relations")]')
print(invest_link)

结果/错误显示:

[]

部分链接:

browser.get("https://www.kbc.com/en.html")
browser.implicitly_wait(30) 
# Locating Hyperlinks by Link Text
invest_link = browser.find_element_by_partial_link_text("Investor").click()
print(invest_link)

结果/错误显示:

Message: no such element: Unable to locate element: {"method":"partial link text","selector":"Investor"}
评论
  • zamet
    zamet 回复

    要获取文本,请尝试以下操作

    import time
    
    from selenium import webdriver
    
    chrome_browser = webdriver.Firefox()
    chrome_browser.get('https://www.kbc.com/en.html')
    time.sleep(5)  # wait for page to load
    
    investor_relations_text = chrome_browser.find_element_by_link_text("Investor Relations")
    print(investor_relations_text.text)