I am attempting to scrape the web page (see code) – as well as those pages going back in time (you can see the date ‘20110509’ in the page itself) – for simple numerical strings. I can’t seem to figure out through much trial and error (I’m new to programming) how to parse the specific data in the table that I want. I have been trying to use simple PHP/HTML without curl or other such things. Is this possible? I think my main issue is
using the delimiters that are necessary to get the data from the source code.
What I’d like is for the program to start at the very first page it can, say for example ‘20050101’, and scan through each page till the current date, grabbing the specific data for example, the “latest close” (column), “closing arm” (row), and have that value for the corresponding date exported to a single .txt file, with the date being separated from the value with a comma. Each time the program is run, the date/value should be appended to the existing text file.
I am aware many lines of the code below are junk, it’s part of my learning process.
<html>
<title>HTML with PHP</title>
<body>
<?php
$rawdata = file_get_contents('http://online.wsj.com/mdc/public/page/2_3021-tradingdiary2-20110509.html?mod=mdc_pastcalendar');
//$data = substr(' ', $data);
//$begindate = '20050101';
//$newlines = array("\t","\n","\r","\x20\x20","\0","\x0B");
//if (preg_match(' <td class="text"> ' , $data , $content)) {
//$content = str_replace($newlines
echo $rawdata;
///file_put_contents( 'NYSETRIN.html' , $content , FILE_APPEND);
?>
<b>some more html</b>
<?php
?>
</body>
</html>
All right so let’s do this. We’re going to first load the data into an HTML parser, then create an XPath parser out of it. XPath will help us navigate around the HTML easily. So:
Now then we need to grab some data. First off let’s get all the data tables. Looking at the source, these tables are indicated by a class of
mdcTable:So far:
Okay so we have the tables. Now we need to get specific column. So let’s use the latest close column you mentioned:
The result so far:
Now we need the column index for getting the specific column for the specific row. We do this by counting all of the previous sibling elements, then adding one. This is because element index selectors are 1 indexed, not 0 indexed:
Result is:
Now we need to get our specific row:
Here we use
starts-with, since the row label has a utf-8 symbol in it. This makes it easier. Result so far:Now we need to use the column index to get the data we want:
Result is:
Which can now be written to a file. Now, we don’t have the markets these apply to, so let’s go ahead and grab those:
Now we can use a counter to reference which market we’re on:
The output being:
Now for your part: