這里是 Selenium 的新手。我在這里先向您的幫助表示感謝!
我正在嘗試單擊無序串列中的 li href 。這是那個無序串列。
<ul id="search_result">
<li>1. <a href="https://www.bookseriesinorder.com/lee-child/" rel="bookmark"
title="Permanent Link to Lee Child">Lee Child</a>
<li>2. <a href="https://www.bookseriesinorder.com/eileen-brady/" rel="bookmark"
title="Permanent Link to Eileen Brady">Eileen Brady</a>
<li>3. <a href="https://www.bookseriesinorder.com/lyla-lee/" rel="bookmark"
title="Permanent Link to Lyla Lee">Lyla Lee</a>
</ul>
這是我正在嘗試使用的代碼。
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
options = Options()
options.page_load_strategy = 'normal' # normal, eager, none
options.add_experimental_option('excludeSwitches', ['enable-logging'])
driver = webdriver.Chrome(options=options)
driver.get("https://www.bookseriesinorder.com/")
# Add code to wait until the search box has been loaded
try:
search = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "s")))
except:
driver.quit()
# Enter the text to search for
author = "Lee Child"
search.send_keys(author)
search.send_keys(Keys.RETURN)
# Find the author link and click it
try:
# search_results = WebDriverWait(driver, 10).until(
# EC.presence_of_element_located((By.XPATH,"//ul[@id='search_result']")))
# search_results = WebDriverWait(driver, 10).until(
# EC.presence_of_element_located((By.XPATH,"//ul[@id='search_result']/a[contains(@href, 'lee-child')]"))).click
search_results = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH,"//ul[@id='search_result']/a[contains(@href, 'lee-child')]")))
except:
driver.quit()
print (search_results)
driver.close()
我正在嘗試單擊 Lee Child 的鏈接。我正在嘗試使用 XPATH,如果不包含串列項,我可以找到 ul。但是當我嘗試添加串列項(因此搜索 Lee Child)時,我收到錯誤“NameError: name 'search_results' is not defined”。
誰能解釋正確的 XPATH 應該是什么才能找到 Lee Child 的鏈接?
提前感謝您的任何和所有指導。
uj5u.com熱心網友回復:
你快到了。
您的代碼的唯一問題是您嘗試單擊的鏈接的 XPath。
該a元素不是 的直接子元素ul,因此它應該在//那里,而不是/。
此外,最好使用element_to_be_clickable而不是presence_of_element_located.
所以,而不是
search_results = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH,"//ul[@id='search_result']/a[contains(@href, 'lee-child')]")))
請試試這個:
search_results = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,"//ul[@id='search_result']//a[contains(@href, 'lee-child')]"))).click()
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/506709.html
上一篇:從Booking.com抓取資訊
下一篇:硒找不到元素
