Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you scrape AJAX pages?

Please advise how to scrape AJAX pages.

like image 453
xxxxxxx Avatar asked Nov 04 '08 01:11

xxxxxxx


People also ask

What is AJAX used for?

What's AJAX? AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files.

Is webpage scraping legal?

Web scraping is legal if you scrape data publicly available on the internet. But some kinds of data are protected by international regulations, so be careful scraping personal data, intellectual property, or confidential data.


1 Answers

Overview:

All screen scraping first requires manual review of the page you want to extract resources from. When dealing with AJAX you usually just need to analyze a bit more than just simply the HTML.

When dealing with AJAX this just means that the value you want is not in the initial HTML document that you requested, but that javascript will be exectued which asks the server for the extra information you want.

You can therefore usually simply analyze the javascript and see which request the javascript makes and just call this URL instead from the start.


Example:

Take this as an example, assume the page you want to scrape from has the following script:

<script type="text/javascript"> function ajaxFunction() { var xmlHttp; try   {   // Firefox, Opera 8.0+, Safari   xmlHttp=new XMLHttpRequest();   } catch (e)   {   // Internet Explorer   try     {     xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");     }   catch (e)     {     try       {       xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");       }     catch (e)       {       alert("Your browser does not support AJAX!");       return false;       }     }   }   xmlHttp.onreadystatechange=function()     {     if(xmlHttp.readyState==4)       {       document.myForm.time.value=xmlHttp.responseText;       }     }   xmlHttp.open("GET","time.asp",true);   xmlHttp.send(null);   } </script> 

Then all you need to do is instead do an HTTP request to time.asp of the same server instead. Example from w3schools.


Advanced scraping with C++:

For complex usage, and if you're using C++ you could also consider using the firefox javascript engine SpiderMonkey to execute the javascript on a page.

Advanced scraping with Java:

For complex usage, and if you're using Java you could also consider using the firefox javascript engine for Java Rhino

Advanced scraping with .NET:

For complex usage, and if you're using .Net you could also consider using the Microsoft.vsa assembly. Recently replaced with ICodeCompiler/CodeDOM.

like image 156
Brian R. Bondy Avatar answered Sep 23 '22 12:09

Brian R. Bondy