Selenium和Python 3:在otto.de上选择一个搜索框

时间:2018-06-02 09:56:08

标签: python-3.x selenium selenium-webdriver

我是Python 3以及网页抓取的新手,我现在有点卡住了 我想:
1.选择otto.de上的搜索框。 2.插入我要搜索的产品编号。
3.按enter或单击搜索按钮。 4.下载以下页面。

otto.de上的搜索字段包含以下源代码:

<form class="p_form js_searchForm focus" action="/suche" data-article-number-search="/p/search/" autocomplete="off" autocorrect="off" spellcheck="false" role="search">
            <input placeholder="Suchbegriff / Artikelnr. eingeben" data-error="Bitte mind. ein Zeichen eingeben" class="p_form__input js_searchField sanSearchInput" type="text" autocomplete="off" autocorrect="off" maxlength="50" disabled>
            <button class="sanSearchDelBtn p_symbolBtn100--4th" type="reset"><i>X</i></button>
            <button class="js_submitButton sanSearchButton" type="submit" title="Suche" disabled ><span>&raquo;</span></button>
</form>

我试图做的事情:

browser = webdriver.Firefox()
browser.get('http://www.otto.de')
elem = browser.find_element_by_xpath("//form[input/@class='p_form__input   js_searchField sanSearchInput']")
elem.send_keys('538707' + Keys.RETURN)
with open("Productpage.txt", "w") as outfile:
    outfile.write(browser.page_source)
browser.quit()

它给我以下错误消息:

selenium.common.exceptions.InvalidElementStateException: Message: Unable    to clear element that cannot be edited: <form class=
"p_form js_searchForm focus"> 

我尝试了很多不同的命令,但我无法进入我需要的页面。有谁知道如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

这是一个有效的代码:

from selenium import webdriver
from selenium.webdriver.support import ui
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time


browser = webdriver.Firefox()
browser.get("http://www.otto.de")

ui.WebDriverWait(browser, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".p_form__input.js_searchField.sanSearchInput"))).send_keys("538707")

ui.WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".js_submitButton.sanSearchButton"))).click()

with open("Productpage.txt", "w", encoding="utf-8") as outfile:

    outfile.write(browser.page_source)

time.sleep(5)

browser.quit()

希望它可以帮到你!