我已经开始为当地房地产网站编写解析器。我已经使用Selenium来选择我需要的页面,但几分钟之后我再也无法访问它,它给了我这个错误:
NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="tr_an-357543"]"}
(Session info: chrome=55.0.2883.87)
(Driver info: chromedriver=2.27.440175 (9bc1d90b8bfa4dd181fbbf769a5eb5e575574320),platform=Linux 4.4.0-21-generic x86_64)
这是一段代码:
driver = webdriver.Chrome()
url = "https://makler.md/md/"
driver.get(url)
driver.maximize_window()
driver.find_element_by_xpath('//*[@id="rublist_lev1"]/li[1]/a').click() # acces Imobiliare
driver.find_element_by_link_text("Vânzare apartamente, camere").click() # acces Apartamente
parentElement = driver.find_element_by_xpath('//*[@id="tr_an-357543"]')
elementList = parentElement.find_elements_by_tag_name("a")
links = []
for element in driver.find_elements_by_xpath('//article[starts-with(@id, "tr_an-")]//a[@class="ls-detail_anUrl"]'):
links.append(element.get_attribute('href'))
page = driver.get(links[15])
caracteristici = driver.find_element_by_xpath('//*[@id="anItemData"]/ul[2]')# Selecteaza blocul caracteristici
print(caracteristici.text)
driver.close()
当我再次粘贴'caracteristici'的x路径时,它正在工作。如何解决这个问题?
答案 0 :(得分:0)
网站加载每个页面似乎需要几秒钟。初始化driver
时,可以隐式等待,等待元素在搜索它们时存在的给定时间(一次初始化)
driver = webdriver.Chrome()
driver.implicitly_wait(10)
或在问题部分
中使用显式等待和expected_conditions
parentElement = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, '//*[@id="tr_an-357543"]'))
供参考waits。