6

splinter 0.7.3在 Linux 平台上使用模块python 2.7.2来使用默认的 Firefox 浏览器在网站上抓取目录列表。

这是通过单击 html 中的“下一步”链接来遍历分页 Web 列表的代码片段。

    links = True
    i = 0
    while links:
        with open('html/register_%03d.html' % i, 'w') as f:
            f.write(browser.html.encode('utf-8'))
        links = browser.find_link_by_text('Next')
        print 'links:', links
        if links:
            links[0].click()
        i += 1

我知道链接正在工作,因为我看到的输出如下所示:

links: [<splinter.driver.webdriver.WebDriverElement object at 0x2e6da10>, <splinter.driver.webdriver.WebDriverElement object at 0x2e6d710>]
links: [<splinter.driver.webdriver.WebDriverElement object at 0x2e6d5d0>, <splinter.driver.webdriver.WebDriverElement object at 0x2e6d950>]
links: [<splinter.driver.webdriver.WebDriverElement object at 0x2e6d710>, <splinter.driver.webdriver.WebDriverElement object at 0x2e6dcd0>]
links: []

当 html 保存在每个页面上时,f.write(browser.html.encode('utf-8'))它适用于第一页。在随后的页面上,虽然我可以看到在 Firefox 中呈现的页面,但html/regiser_...html文件为空或缺少正文标记,如下所示:

<!DOCTYPE html>
<!--[if lt IE 7]>      <html prefix="og: http://ogp.me/ns#" class="no-js lt-ie9 lt-ie8 lt-ie7"  lang="en-gb"> <![endif]-->
<!--[if IE 7]>         <html prefix="og: http://ogp.me/ns#" class="no-js lt-ie9 lt-ie8"  lang="en-gb"> <![endif]-->
<!--[if IE 8]>         <html prefix="og: http://ogp.me/ns#" class="no-js lt-ie9"  lang="en-gb"> <![endif]-->
<!--[if gt IE 8]><!-->
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-gb" class="no-js" prefix="og: http://ogp.me/ns#"><!--<![endif]--><head>
        <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible" />    
    ...
  </style>
  <script src="/media/com_magebridge/js/frototype.min.js" type="text/javascript"></script></head></html>

这是从 splinter 中保存 html 的已知功能吗?有更好的方法吗?

4

1 回答 1

3

它确实看起来像一个时间问题 -当页面未完全加载时,您正在获取页面源。有几种方法可以解决这个问题:

  • 等待body 出现

    browser.is_element_present_by_tag("body", wait_time=5)
    
  • 增加页面加载超时- 在初始化browser对象后立即放置:

    browser.driver.set_page_load_timeout(10)  # 10 seconds
    
于 2016-01-01T06:04:47.647 回答