2016-08-02 63 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,但如果我想遵守,我就无能为力了 –