2016-09-30 82 views
-2

我想在多個網站上提交表格。通常我不能完全知道表單名稱或表單ID,但我知道要提交的輸入名稱。根據表格輸入的名稱選擇正確的表格

假設有一個網站裏面有幾個表單。我的代碼應該檢查所有表單,如果其中一個表單有一個名爲「birthday」的輸入值,它將提交該表單。如果有多個表單,它會將它們全部提交。

我該如何做到這一點?

回答

1

你基本上可以遍歷所有形式和跳過那些不包含所需的輸入形式:

for form in br.forms(): 
    if not form.find_control(name="birthday"): 
     continue 
    # fill form and submit here 

更多find_control()here

+0

所以我怎麼能選擇的形式,因爲我不知道表單名? –

+0

@RobertZunr就是我所說的,遍歷所有這些並過濾。 – alecxe

+0

我在跳過沒有「生日」輸入的表單。但其餘的呢。我如何找到提交「生日」值的表單名稱 –

0

你將需要使用iterator來檢查網站上的所有表格。在這種情況下,我們將使用for。但是,這並不讓我們知道我們正在使用哪種形式,它只是讓我們使用它。所以我們將把0(第一個表單的ID)賦給一個變量,並且在新的迭代/循環開始時我們改變表單的時候給它加1。

currentForm = 0 
for form in br.forms(): # For every form in the website 
     currentForm += 1 # Add 1 to the current form so that the script knows which form we will be working next 
     if not forms.find_control(name = "birthday"): # If the form isn't about birthday 
       continue # Go to the next iteration/loop ignoring the statements below 
     br.select_form(nr = currentForm) # Select the birthday form 
     br.form["birthday"] = "Fill this with what you want" # Writing to the form 
     br.submit() # Submit the working form 

注:x += y等於x = x + y