Spynner:提交表单后获取第二页的html

时间:2013-03-18 12:03:03

标签: python web-scraping spynner

我刚刚开始使用Spynner来抓取网页,但我没有找到任何好的教程。我在这里有一个简单的例子,我在Google中输入一个单词,然后我想查看结果页面。

但是如何从点击按钮到实际获取新页面呢?

import spynner

def content_ready(browser):
    if 'gbqfba' in browser.html:
        return True #id of search button

b = spynner.Browser()
b.show()
b.load("http://www.google.com", wait_callback=content_ready)
b.wk_fill('input[name=q]', 'soup')
# b.browse() # Shows the word soup in the input box
with open("test.html", "w") as hf: # writes the initial page to a file
    hf.write(b.html.encode("utf-8"))
b.wk_click("#gbqfba") # Clicks the google search button (or so I think)

但现在呢?我甚至不确定我是否点击了谷歌搜索按钮,虽然它确实有id = gbqfba。我也尝试过b.click(“#gbqfba”)。如何获得搜索结果?

我尝试过这样做:

 with open("test.html", "w") as hf: # writes the initial page to a file
    hf.write(b.html.encode("utf-8"))

但仍会打印初始页面。

2 个答案:

答案 0 :(得分:2)

我通过将Enter发送到输入并等待两秒来解决这个问题。不理想,但它有效

import spynner
import codecs
from PyQt4.QtCore import Qt

b = spynner.Browser()
b.show()
b.load("http://www.google.com")
b.wk_fill('input[name=q]', 'soup')
# b.browse() # Shows the word soup in the input box

b.sendKeys("input[name=q]",[Qt.Key_Enter])
b.wait(2)
codecs.open("out.html","w","utf-8").write(b.html)

答案 1 :(得分:1)

推荐的方法是等待加载新页面:

b.wait_load()
相关问题