我正在尝试使用Selenium Webdriver Chrome从以下HTML代码段中选择并单击href中的链接。但是我收到了NoSuchElement异常



<a href="http://www.legislation.vic.gov.au/Domino\Web_Notes\LDMS\PubStatbook.nsf?opendatabase" alt="Victorian Statute Book" onmouseover="document.images[&quot;StatBook&quot;].src=&quot;/domino/web_notes/LDMS/pubhome.nsf/goldRightImage.gif&quot;" onmouseout="document.images[&quot;StatBook&quot;].src=&quot;/domino/web_notes/LDMS/pubhome.nsf/goldLeftImage.gif&quot;" onclick="top.frames['TopWeb2'].document.getElementById('CurrentDB').innerHTML='Currently&nbsp;in&nbsp;Statute&nbsp;Book'"><img src="/domino/web_notes/LDMS/pubhome.nsf/goldLeftImage.gif" name="StatBook" alt="" border="0" onclick="top.frames['TopWeb2'].document.getElementById('CurrentDB').innerHTML='Currently&nbsp;in&nbsp;Statute&nbsp;Book'">
<img src="/domino/web_notes/LDMS/pubhome.nsf/VicStat_title.gif" alt="Statute Book" border="0"></a>





这是我的Python代码:

   import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import TimeoutException
import csv
options = webdriver.ChromeOptions()
prefs = {
    'download.default_directory':
    r'D:\LEG_DOWNLOAD\CTH NEW'
}
options.add_experimental_option('prefs', prefs)
browser = webdriver.Chrome(executable_path=r'D:\CHROME\chromedriver.exe', chrome_options=options)
browser.get('http://www.legislation.vic.gov.au/')

with open(r"D:\LEG_DOWNLOAD\VIC.csv") as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')

    # Skip the heading line
    readCSV.__next__()

    for row in readCSV:
        acts = row[0:616]
        element = browser.find_element_by_xpath("//a[@href='http://www.legislation.vic.gov.au/Domino\Web_Notes\LDMS\PubStatbook.nsf?opendatabase']")
        element.click()
        time.sleep(2)
browser.back()
time.sleep(2)
browser.quit()


我收到以下异常

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//a[@href='http://www.legislation.vic.gov.au/Domino\Web_Notes\LDMS\PubStatbook.nsf?opendatabase']"}
  (Session info: chrome=74.0.3729.169)
  (Driver info: chromedriver=71.0.3578.137 (86ee722808adfe9e3c92e6e8ea746ade08423c7e),platform=Windows NT 6.1.7601 SP1 x86_64)


您能告诉我我在做什么错吗?

最佳答案

页面有时间加载吗?可能是webdriver无法定位元素,因为尚未加载。

关于python - Selenium Webdriver未单击Href链接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56677874/

10-13 08:47