简体   繁体   中英

Selenium/python - “find partial link text ” and “xpath”

I'm new to the Selenium package. I've 2 problems when try to identify if a given text exist on website. website address:

www.kbc.com 

I need to get the text "Investor Relations" on their menu bar. But keeps failures. Please help me have a check. Thanks.

You can also find part of the elements here:

<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>

the packages installed:

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)

The result/error shows:

[]

partial 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)

The result/error shows:

Message: no such element: Unable to locate element: {"method":"partial link text","selector":"Investor"}

You are clicking on the link, To get the text try the following

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)

Or try get_attribute("innerHTML")

print(investor_relations_text.get_attribute("innerHTML"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM