【问题标题】:Why selenium's click method is returning NoSuchElementException?为什么 selenium click 方法返回 NoSuchElementException?
【发布时间】:2018-10-07 08:16:31
【问题描述】:

在抓取 javascript 基础网站 (link) 期间,我坚持使用无法产生预期结果的点击功能。我已经粘贴了应该在“适合以下汽车”下拉菜单下返回数据的代码,但出乎意料的是,它只是打印了 except 语句的消息。我能够从同一代码中抓取所有其他数据。我是否应该再添加几行以使数据隐藏在该下拉列表下,如果是,那么要添加哪些行。

def product(self,response):
    while True:
        try:
            drop=self.driver.find_element_by_xpath('//*[@id="toggleMakeModelArrow"]')
            self.logger.info('Sleep for 3 sec.')
            sleep(3)
            drop.click()
            sel=Selector(text=self.driver.page_source)
            drop_down=sel.xpath('//*[@id="CachedItemDispaly_make_model_div"]/select/option/text()').extract()
            for i in range(len(drop_down)):
                print drop_down[i]+"||"

        except NoSuchElementException:
            self.logger.info('No more Fits the following cars to load..')
            break

【问题讨论】:

标签: python-2.7 selenium scrapy-spider


【解决方案1】:

您不断收到NoSuchElementException 的原因是下拉列表被动态插入到DOM 树中,因此您需要等待一段时间才能使用它。实现等待超时的最好方法是使用python-selenium提供的wait API

这是一个工作代码,其中time.sleep 被用作临时解决方案。

from selenium.webdriver.support.ui import Select
from selenium import webdriver
import time


driver = webdriver.Chrome()
driver.get("https://portal.orio.com/webapp/wcs/stores/servlet/ProductDisplay?urlRequestType=Base&productId=218044&catalogId=10051&categoryId=146003&errorViewName=ProductDisplayErrorView&urlLangId=-150&langId=-150&top_category=146001&parent_category_rn=146001&storeId=11901")

drop=driver.find_element_by_xpath('//*[@id="toggleMakeModelArrow"]')

time.sleep(5)
drop.click()
time.sleep(5)
select = Select(driver.find_element_by_class_name('orioVehicleMakeModeltypeInfo'))

for select_option in select.options:
    print(select_option.text)

【讨论】:

    猜你喜欢
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 2015-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多