【问题标题】:mechanize._mechanize.FormNotFoundError: no form matching name 'q'mechanize._mechanize.FormNotFoundError:没有匹配名称“q”的表单
【发布时间】:2013-04-15 16:23:01
【问题描述】:

谁能帮我正确选择这个表单?

试图爬取谷歌,我得到了错误: mechanize._mechanize.FormNotFoundError: no form match name 'q'

不寻常,因为我看过其他几个使用它的教程,并且: p.s.我不打算用请求来 SLAM google,只是希望使用自动选择器来不时查找学术引文 pdf。

<f GET http://www.google.com.tw/search application/x-www-form-urlencoded
  <HiddenControl(ie=Big5) (readonly)>
  <HiddenControl(hl=zh-TW) (readonly)>
  <HiddenControl(source=hp) (readonly)>
  <TextControl(q=)>
  <SubmitControl(btnG=Google ?j?M) (readonly)>
  <SubmitControl(btnI=?n???) (readonly)>
  <HiddenControl(gbv=1) (readonly)>>
>>> quit()




import os, subprocess
import re
import mechanize
from bs4 import BeautifulSoup
#prepare mechanize
br = mechanize.Browser()
br.set_handle_robots(False)
br.set_handle_equiv(False)
br.addheaders = [('User-agent', 'Mozilla/5.0')] 
br.open('http://www.google.com/')
br.select_form('q')
citation = ' www.stackoverflow.com '.strip() 
#citation = GOOGLE_BASE + Citation
print citation
br.open('http://www.google.com/')
br.select_form('q')
br.form['q'] = citation
br.submit()
data = br.read()
soup = BeautifulSoup(data)
print soup

【问题讨论】:

    标签: python forms web-crawler mechanize


    【解决方案1】:

    您正在尝试选择一个名为 q 的表单,但该表单不存在。似乎该表单被命名为f。 (但是,我无法在我的浏览器中验证这一点——即使禁用了 Javascript,我也只能看到不同的名称。)

    一个简单的谷歌搜索可以这样完成:

    import os, subprocess
    import re
    import mechanize
    from bs4 import BeautifulSoup
    
    #prepare mechanize
    br = mechanize.Browser()
    br.set_handle_robots(False)
    br.set_handle_equiv(False)
    br.addheaders = [('User-agent', 'Mozilla/5.0')] 
    br.open('http://www.google.com/')
    
    # do the query
    br.select_form(name='f')   # Note: select the form named 'f' here
    br.form['q'] = 'here goes your query' # query
    data = br.submit()
    
    # parse and output
    soup = BeautifulSoup(data.read())
    print soup
    

    这应该会给你这个想法。

    更新:如何找到正确的表单“选择器”

    要打印可用表单的名称,您可以:

    for form in br.forms():
        print form.name
    

    这在您使用交互式控制台时会派上用场。

    您不必使用表单的名称,但您可以提供其他提示以选择正确的表单。例如,在某些页面上,表单根本没有名称。然后您仍然可以根据表格的编号进行选择,例如br.select_form(nr=1) 用于页面上的第二个表单。详情请见help(br.select_form)。此外,list(br.forms()) 将为您提供所有表单的列表,您可以进一步检查。

    另一种选择是在常用浏览器中手动检查页面。

    【讨论】:

    • 将来如果谷歌要更改表单的名称,或者对于其他类似的网站,您能告诉我如何获取表单名称吗?
    猜你喜欢
    • 2016-07-20
    • 1970-01-01
    • 2012-12-07
    • 1970-01-01
    • 2011-01-16
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多