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

2 投票
2 回答
1679 浏览
提问于 2025-04-17 19:29

我刚开始使用Spynner来抓取网页,但找不到什么好的教程。这里有一个简单的例子,我在谷歌上输入一个词,然后想看看结果页面。

但是,我该怎么从点击按钮到真正获取新页面呢?

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 个回答

1

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

b.wait_load()
2

我通过在输入框里发送一个回车键,然后等了两秒钟来解决这个问题。这不是最好的方法,但确实有效。

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)

撰写回答