【问题标题】:Python / parsing: BeautifulSoup error "module obj is not callable" with results from MechanizePython / 解析:BeautifulSoup 错误“模块 obj 不可调用”,结果来自 Mechanize
【发布时间】:2012-06-09 20:00:36
【问题描述】:

BeautifulSoup 和我无法识别 br.response().read() 的结果。 我已经导入 BeautifulSoup

#snippet:
# Select the first (index zero) form
br.select_form(nr=0)
br.form.set_all_readonly(False)
br['__EVENTTARGET'] = list_of_dates[0]
br['__EVENTARGUMENT'] = 'calMain'
br['__VIEWSTATE'] = viewstate
br['__EVENTVALIDATION'] = eventvalidation

response = br.submit()
print br.response().read() #*#this prints the html I'm expecting*

soup = BeautifulSoup(br.response().read()) #*#but this throws 
#TypeError: 'module' object is not callable.  
#Yet if I call soup = BeautifulSoup("http://page.com"), it's cool.*

selecttable = soup.find('table',{'id':"tblItems"})
#/snippet

...等等

所以我觉得我有错误的“对象”,但是,BeautifulSoup 想要什么样的“对象”?

【问题讨论】:

  • 你用什么import语句来导入美汤?
  • 您更新的脚本再次执行 br.response.read() 两次。您需要致电BeautifulSoup(raw)。你应该只调用一次 response.read 。此外,您可能不应该调用模块对象,而应该在响应对象上调用它。
  • 所以我已经完全去掉了“cooked”,现在调用 BeautifulSoup(raw)。现在用一些非虚拟数据对此进行测试。谢谢!!

标签: python beautifulsoup mechanize


【解决方案1】:

使用

from BeautifulSoup import BeautifulSoup

代替

import BeautifulSoup

否则我认为你在做正确的事!

【讨论】:

    【解决方案2】:

    你写道:

    response = br.submit()
    print br.response().read() #*#this prints the html I'm expecting*
    
    soup = BeautifulSoup(br.response().read())
    

    你为什么不试试:

    response = br.submit()
    soup = BeautifulSoup(response.read())
    

    我怀疑这与您在 br.response() 上调用 .read() 的事实有关,在我使用 mechanize 的历史中,我总是将 response() 保存到一个变量中并从那里。我不知道它会起作用,也不能完全解释为什么print br.response().read() 起作用,但试一试。

    另外,BeautifulSoup 的 HTML 解析器可能不喜欢提供给它的机械化。您可以尝试使用a different parser

    【讨论】:

    • 同意你的观点+指定解析器也可能有帮助。
    【解决方案3】:

    只需确认您的导入是这样的:

    from BeautifulSoup import BeautifulSoup
    

    或者对于 BeautifulSoup4

    from bs4 import BeautifulSoup
    

    【讨论】:

      【解决方案4】:

      您是否尝试过只读取对象一次然后保存结果。

      例如:

      raw = br.response().read()
      
      soup = BeautifulSoup(raw)
      

      使用文件对象,您可以读取它们一次,然后必须重新打开它们才能再次读取。看起来您正在阅读它们两次。您应该做的另一件事是在阅读前后打印 br.response 的类型签名。

      为了更容易调试,尝试打印类型签名:

      print type(response) # see the type of response from above
      raw = br.response().read()
      print type(raw)
      print type(br.response().read()) # see what happens the second time :P
      

      此外,如果您也发布堆栈跟踪信息也会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-06
        • 2018-02-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-17
        • 2015-08-08
        • 1970-01-01
        • 2014-07-01
        相关资源
        最近更新 更多