Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse Website for URLs

Just wondering if someone can help me further with the following. I want to parse the URL on this website:http://www.directorycritic.com/free-directory-list.html?pg=1&sort=pr

I have the following code:

<?PHP  
$url = "http://www.directorycritic.com/free-directory-list.html?pg=1&sort=pr";
$input = @file_get_contents($url) or die("Could not access file: $url"); 
$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>"; 
if(preg_match_all("/$regexp/siU", $input, $matches)) { 
// $matches[2] = array of link addresses 
// $matches[3] = array of link text - including HTML code
} 
?>

Which does nothing at present and what I need this to do is scrap all the URL in the table for all 16 pages and would really appreciate some help with how to amend the above to do that and output URL into a text file.

like image 546
Bill Johnson Avatar asked Dec 16 '10 13:12

Bill Johnson


People also ask

Is website parsing legal?

Good news for archivists, academics, researchers and journalists: Scraping publicly accessible data is legal, according to a U.S. appeals court ruling.

Can you web scrape any website?

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. Respect your target websites and use empathy to create ethical scrapers.

What is scraping a URL?

Web scraping is the process of using bots to extract content and data from a website. Unlike screen scraping, which only copies pixels displayed onscreen, web scraping extracts underlying HTML code and, with it, data stored in a database. The scraper can then replicate entire website content elsewhere.


1 Answers

Use HTML Dom Parser

$html = file_get_html('http://www.example.com/');

// Find all links
$links = array(); 
foreach($html->find('a') as $element) 
       $links[] = $element->href;

Now links array contains all URLs of given page and you can use these URLs to parse further.

Parsing HTML with regular expressions is not a good idea. Here are some related posts:

  • Using regular expressions to parse HTML: why not?
  • RegEx match open tags except XHTML self-contained tags

EDIT:

Some Other HTML Parsing tools as described by Gordon in comments below:

  • phpQuery
  • Zend_Dom
  • QueryPath
  • FluentDom
like image 197
Naveed Avatar answered Nov 05 '22 18:11

Naveed