2016-08-02 75 views
1

我需要在提交搜索表單後在網站上執行某些操作。問題是,當我通過瀏覽器執行此操作時,頁面不會重新加載,也不會重定向到任何位置:結果顯示在搜索表單下方,不會對鏈接進行任何更改,但我可以在「新」頁面中看到它們HTML。 但是當我使用下面的代碼,我不能看到「新」的頁面HTML應該是在響應(提供的鏈接是一個我其實是想用工作):Python3:通過MechanicalSoup提交表單時沒有任何反應

import mechanicalsoup 

def fetchfile(query): 

    url = "http://www.italgiure.giustizia.it/sncass/" 

    browser = mechanicalsoup.Browser() 
    page = browser.get(url) 
    search_form = page.soup.find("form", {"id": "z-form"}) 
    search_form.find("input", {"id":"searchterm"})["value"] = query 
    response = browser.submit(search_form, page.url) 

    print(response) # the response is 200, so it should be a good sign 

    # actual parsing will come later... 
    print("1235" in response.text) # quick-check to see if there is what I'm looking for, but I get False 

    # in fact this... 
    print(page.text == response.text) # ...gives me True 

fetchfile("1235/2012") 

我可以不明白我錯過了什麼。我寧願不使用硒。任何線索?

回答

0

我剛剛完成同樣的問題掙扎。我對Python也很新,所以讓我試着解釋一下。

您正在「查找」頁面上的元素,但您需要從表單搜索中獲取結果並將其轉換爲Form對象,然後可以設置表單對象的值並提交它。在您提交後沒有收到任何回覆的原因是因爲您的表單值實際上沒有設置,您只是在進行搜索。我知道這個問題很老,但希望這也能幫助其他人。我不知道「查詢」的實際價值是什麼,所以我無法驗證它的工作原理,但在我的程序中,這是我使用的方法。

import mechanicalsoup 
import html5lib 
from bs4 import BeautifulSoup 

def fetchfile(query): 

    url = "http://www.italgiure.giustizia.it/sncass/" 

    browser = mechanicalsoup.Browser() 
    page = browser.get(url) 

    # Using page.find() with the appropriate attributes is also useful 
    # for forms without names 
    FORM = mechanicalsoup.Form(page.find('form', attrs={'id': 'z-form'})) 

    FORM["searchterm"] = query 

    # You can verify the form values are set by doing this: 
    print("Form values: ", vars(FORM)) 

    response = browser.submit(FORM, url) 

    print(response) # the response is 200, so it should be a good sign 
    Results = browser.get_current_page() 
    print("Results: ", Results) 

    # actual parsing will come later... 
    # quick-check to see if there is what I'm looking for, but I get False 
    # print("1235" in response.text) 

    # in fact this... 
    print(page.text == response.text) # ...gives me True 

# fetchfile("1235/2012") 
+0

感謝您的回答,但最終我不得不使用硒,因爲提交結果後,我需要下載PDF文件......,似乎沒有其他方式比使用硒和「點擊「那些結果。我的新問題是robots.txt,但如果我想遵守,我就無能爲力了 –