【问题标题】:Selenium/python - "find partial link text " and "xpath"Selenium/python - “查找部分链接文本”和“xpath”
【发布时间】:2020-07-21 11:54:26
【问题描述】:

我是 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"}

【问题讨论】:

  • 您需要链接还是文本?你用的是什么浏览器?
  • @0m3r 我需要文本。我正在使用铬

标签: python html selenium


【解决方案1】:

您正在单击链接,要获取文本,请尝试以下操作

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)

或者试试get_attribute("innerHTML")

print(investor_relations_text.get_attribute("innerHTML"))

【讨论】:

  • 我以前试过。 “by_link”或“partial_link”都可以。
猜你喜欢
  • 2017-03-17
  • 2022-08-10
  • 1970-01-01
  • 2021-10-31
  • 1970-01-01
  • 1970-01-01
  • 2018-12-14
  • 1970-01-01
  • 2022-07-13
相关资源
最近更新 更多