2013-05-13 62 views
3

我在Selenium的帮助下编写了一个Scrapy蜘蛛来处理网页上的Javascript内容。但是,我意识到这个蜘蛛比普通的Scrapy Crawler慢得多。 由于这个原因,我想结合两个蜘蛛:常见的CrawlSpider获得所有资源和一个Selenium蜘蛛只是为了广泛使用JavaScript的页面。我创建了 pipleline步骤,尝试检测网页是否需要JavaScript并大量使用它。到目前为止 我对处理步骤的想法失败:如何检测页面是否大量使用JavaScript,Python,Scrapy和Selenium?

  • 某些页面使用常见的<noscript>标记。
  • 某些页面打印警告消息,例如<div class="yt-alert-message" >
  • ...

有这么多不同的方式来表明一个页面需要安装Javascript!

  • 你知道一个标准化的方式,我怎么能“检测”,这广泛使用 JavaScript的网页?

注:我只想要处理我的硒蜘蛛网页,确实有必要 如蜘蛛显著慢,一些网页只用它的一个不错的设计。

+0

您是否尝试过[机械化](http://wwwsearch.sourceforge.net/mechanize/)这些广泛使用js页面? – alecxe 2013-05-13 21:32:41

回答

2

您可以从脚本标记中获取所有JavaScript,将其全部添加,并检查长度不超过您认为构成“大量”JavaScript的数量。

# get all script tags 
scripts = browser.find_elements_by_tag_name("script") 

# create a string to add all the JS content to 
javaScriptChars = ""; 

# create an list to store urls for external scripts 
urls = list() 

# for each script on the page... 
for script in scripts 

    # get the src 
    url = script.get_attribute("scr") 

    # if script is external (has a 'src' attribute)... 
    if url.__len__() > 0: 

     # add the url to the list (will access it later) 
     urls.append(url) 

    else: 

     # the script is inline - so just get the text inside 
     javaScriptChars = javaScriptChars + script.getAttribute("textContent"); 

# for each external url found above... 
for url in urls 

    # open the script 
    driver.get(url) 

    # add the content to our string 
    javaScriptChars = javaScriptChars + driver.page_source 

# check if the string is longer than some threshold you choose        
if javaScriptChars.__len__() > 50000: 
    # JS contains more than 5000 characters 

该数字是任意的。我猜JS的不到50000个字符实际上可能不是“很多”,因为该页面可能不会每次调用每个函数。这可能会取决于用户的用途。

但是,如果您可以假设精心设计的网站只包含必要的脚本,那么字符数仍然可以作为它运行多少JS的相关指标。

相关问题