元素不在python中

2024-04-26 20:42:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有硒脚本的基本目标,把位置在输入标签,点击搜索按钮,打开结果页,但我有问题,在寻找输入和搜索按钮 剧本如下

# -*- 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列表中一个接一个地获取位置,将其放入输入标记中,然后单击search按钮 并按照步骤进行操作,直到循环完成

我在Chrome和Firefox中都尝试过,但都给出了相同的错误,即元素不在其中


Tags: fromhttpsimportsearchwwwseleniumnllocation
1条回答
网友
1楼 · 发布于 2024-04-26 20:42:40

html中有iframe标记,所以需要使用switch\来实现web驱动程序的功能

在上述情况下,它是这样使用的

# 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 ........

相关问题 更多 >