首页 文章

元素不是selenium python

提问于
浏览
0

我有selenium脚本,基本目标是将位置放在输入标签中并单击搜索按钮并打开结果页面但是我在查找输入和搜索按钮时遇到问题脚本在下面

# -*- coding: utf-8 -*-

import csv
from lxml import html
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def search_location():
    for typ in TYPESOFR:
        for loc in LOCATIONS:
            MAINBROWSER.get(typ)
            elm = WebDriverWait(MAINBROWSER, 10).until(EC.presence_of_element_located((By.ID, 'localisation')))         
            location = MAINBROWSER.find_element_by_id("localisation")
            location.click()
            location.send_keys(loc)
            search = MAINBROWSER.find_element_by_xpath('.//button[@class="sendsearch btn-blue"]')
            MAINBROWSER.execute_script("arguments[0].click();", search)

def main():
    search_location()


if __name__ == '__main__':
    # Links of types of real estates
    TYPESOFR = [
        'https://www.immoweb.be/nl/immo/huis/te-huur',
        'https://www.immoweb.be/nl/immo/appartement/te-huur',
        'https://www.immoweb.be/nl/immo/handelspand/te-huur',
        'https://www.immoweb.be/nl/immo/kantoor/te-huur',
        'https://www.immoweb.be/nl/immo/industrie/te-huur',
        'https://www.immoweb.be/nl/immo/garage/te-huur',
        'https://www.immoweb.be/nl/immo/ander/te-huur',]

    LOCATIONS = ['9000', '2000', '1000']


    chromeOptions = webdriver.ChromeOptions()
    # Disable image loading on page it will load page faster
    prefs = {"profile.managed_default_content_settings.images":2}
    chromeOptions.add_experimental_option("prefs",prefs)
    MAINBROWSER = webdriver.Chrome(chrome_options=chromeOptions)

    # MAINBROWSER = webdriver.Firefox()

    # BROWSER = webdriver.Chrome()
    main()

代码基本上是从 TYPESOFR 列表中逐个获取URL并打开链接并从 LOCATIONS 列表中逐个获取位置并将其放入输入标记然后单击搜索按钮并按照步骤操作直到循环完成

我在Chrome和Firefox中都尝试过同样的错误,因为它没有找到元素

1 回答

  • 1

    html中有iframe标签,所以需要使用web驱动的switch_to功能

    在上面的例子中,它是这样使用的

    # Switching to searh iFrame
    MAINBROWSER.switch_to.frame(MAINBROWSER.find_element_by_xpath('.//*[@id="IWEB_IFRAME_ID_SEARCH"]'))
    
    # no input tag can be located by existing line
    location = MAINBROWSER.find_element_by_id("localisation")
    # ....... other logics ........
    

相关问题