如何等到硒python中的元素可用
Posted
技术标签:
【中文标题】如何等到硒python中的元素可用【英文标题】:How to wait until element is available in selenium python 【发布时间】:2017-10-28 19:45:45 【问题描述】:我正在使用 selenium python 编写脚本,但我试图找到解决方案但我找不到对我有帮助的问题。这是代码
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import unittest
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
class sulekhastart(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def test_parse_contact_urls_and_go_to_next_page(self):
pagenumber = 'Page'
#assign WEBDRIVER to local webdriver
driver = self.driver
#Website open by below url
driver.get("http://www.sulekha.com/ac-dealers/bangalore")
self.assertIn("Sulekha Bangalore", driver.title)
#close the lightbox thnat appears at the firsttime load of page
startlightbox = driver.find_element_by_xpath('//a[@class="lcf-close"]')
startlightbox.click()
while True:
#get the page number
pageno = driver.find_element_by_xpath('//li[@id="numberPage"]/strong')
print pageno.text
print pagenumber
#check if page same as last page or not
if str(pageno.text) != pagenumber:
pagenumber = str(pageno.text)
businessname = driver.find_elements_by_xpath('//li/div/div[@class="busi-name"]/h3/a')
records = len(businessname)
#print all data that are available on the webpage
for i in range(0,records):
print businessname[i].get_attribute('href')
print businessname[i].text
nextpage = driver.find_element_by_xpath('//li[@id="nextPage"]')
nextpage.click()
else:
print 'This is last page all data is scraped change url and get another data'
break
element = WebDriverWait(driver, 10).until_not(EC.presence_of_element_located((By.XPATH, "/html/body/div/div/svg")))
def tearDown(self):
self.driver.close()
print 'page not be closed'
if __name__ == "__main__":
unittest.main()
我想在单击下一个按钮后等待脚本,直到 By.XPATH, "/html/body/div/div/svg"
这个元素从 DOM 或页面源中消失,然后等到 3 秒后
【问题讨论】:
改用"/html/body/div/div/*[name()='svg']"
相信我,试试吧:)))
嘿,谢谢它正在工作@Andersson
【参考方案1】:
正如andersson 评论的那样
替换
element = WebDriverWait(driver, 10).until_not(
EC.presence_of_element_located((
By.XPATH, "/html/body/div/div/svg")))
与
element = WebDriverWait(driver, 10).until_not(
EC.presence_of_element_located((
By.XPATH, "/html/body/div/div/*[name()='svg']")))
解决问题
【讨论】:
以上是关于如何等到硒python中的元素可用的主要内容,如果未能解决你的问题,请参考以下文章
如何解决硒循环中的这个错误? InvalidSelectorException:消息:无效选择器:无法使用 xpath 定位元素