我想用
Python来抓取网页上的“你在找这些作者:”框的内容,如下所示:
http://academic.research.microsoft.com/Search?query=lander
不幸的是,该框的内容由JavaScript动态加载.通常在这种情况下,我可以阅读Javascript来弄清楚发生了什么,或者我可以使用像Firebug这样的浏览器扩展来确定动态内容的来源.这次没有这样的运气…… Javascript非常复杂,Firebug没有提供很多关于如何获取内容的线索.
有什么技巧可以让这项任务变得简单吗?
解决方法
您可以使用ghost.py直接与页面上的JavaScript进行交互,而不是尝试对其进行逆向工程.
如果您在Chrome控制台中运行以下查询,您将看到它返回您想要的所有内容.
document.getElementsByClassName('inline-text-org');
返回
[<div class="inline-text-org" title="University of Manchester">University of Manchester</div>,<div class="inline-text-org" title="University of California Irvine">University of California ...</div> etc...
您可以使用ghost.py在真实DOM中通过python运行JavaScript.
这真的很酷:
from ghost import Ghost ghost = Ghost() page,resources = ghost.open('http://academic.research.microsoft.com/Search?query=lander') result,resources = ghost.evaluate( "document.getElementsByClassName('inline-text-org');")