简体   繁体   English

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

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

I'm new to the Selenium package.我是 Selenium package 的新手。 I've 2 problems when try to identify if a given text exist on website.尝试确定网站上是否存在给定文本时,我遇到了 2 个问题。 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 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")或尝试get_attribute("innerHTML")

print(investor_relations_text.get_attribute("innerHTML"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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