Home Backend Development PHP Tutorial Use curl and regular expressions to crawl web data

Use curl and regular expressions to crawl web data

Jul 25, 2016 am 08:48 AM

Using curl and regular expressions, we built a novel grabber for non-VIP chapters of the Motie Chinese website. It supports inputting the novel ID to download the novel.
Dependencies: curl
You can take a brief look at it. Curl, regular expressions, ajax and other technologies are used in it, which is suitable for novices.When testing locally, you must ensure that you are connected to the Internet and make sure that PHP turns on curl mode.
  1. session_start();
  2. //Encapsulate into a class to start these automatically crawled articles
  3. #header("Refresh:30;http://www.test.com:8080");
  4. class SpiderTools{
  5. ///////////////////////////////////////////////// ////////////////////////////////////////////////////// //////////
  6. /*Input the article ID and parse out the article title*/
  7. ///////////////////////////// ////////////////////////////////////////////////////// //////////////////////////////
  8. public function getBookNameById($aid){
  9. //Initialize curl
  10. $ch= curl_init() ;
  11. //url
  12. $url='http://www.motie.com/book/'.$aid;
  13. if(is_numeric($aid)){
  14. //Regular expression matching
  15. $ru="/ s*(.*)s*s*/";
  16. }
  17. else {
  18. //The family’s survival in the zombie outbreak_The first chapter of the zombie outbreak is updated for my friend Ai Leer~_Sharpening Iron
  19. $ru="/(.*) /";
  20. }
  21. //Set options, including URL
  22. curl_setopt($ch, CURLOPT_URL, $url);
  23. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//Do not automatically output content
  24. curl_setopt( $ch, CURLOPT_HEADER, 0); //Does not return header information
  25. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 0);
  26. //Execute curl
  27. $output = curl_exec($ch);
  28. //Error message
  29. if(curl_exec ($ch) === false){
  30. die(curl_error($ch));
  31. }
  32. // Check if an error occurs
  33. if(curl_errno($ch)){
  34. echo 'Curl error: ' . curl_error( $ch);
  35. }
  36. //Release curl handle
  37. curl_close($ch);
  38. $arr=array();
  39. preg_match_all($ru,$output,$arr);
  40. return $arr[1][0] ;
  41. }
  42. //////////////////////////////////////////////// ////////////////////////////////////////////////////// //////////
  43. /*Input the article ID to parse the article content*/
  44. ///////////////////////////// ////////////////////////////////////////////////////// ///////////////////////////////
  45. public function getBookContextById($aid){
  46. //Start parsing the article
  47. $ids=array( );
  48. $ids=explode("_",$aid);
  49. $titleId=trim($ids[0]);
  50. $aticleId=trim($ids[1]);
  51. $ch= curl_init();
  52. $ru="/
    [sS]*
    [sS]*(.*)/ui"; 
  53. $url='http://www.motie.com/book/'.$aid;
  54. //Regular expression matching
  55. //Set options, including URL
  56. curl_setopt($ch, CURLOPT_URL, $url);
  57. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//Do not automatically output content
  58. curl_setopt($ch, CURLOPT_HEADER, 0);//Do not return header information
  59. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 0 );
  60. //Execute curl
  61. $output = curl_exec($ch);
  62. //Error message
  63. if(curl_exec($ch) === false){
  64. die(curl_error($ch));
  65. }
  66. / / Check if an error occurred
  67. if(curl_errno($ch)){
  68. echo 'Curl error: ' . curl_error($ch);
  69. }
  70. $arr=array();
  71. $arr2=array();
  72. preg_match_all ($ru,$output,$arr);
  73. curl_close($ch);
  74. #var_dump($arr);
  75. $s=$arr[0][0];
  76. $s=substr($s,180) ;
  77. $arr2=explode(" return trim($arr2[0]);
  78. }
  79. ////////////////// ////////////////////////////////////////////////////// /////////////////////////////////////////
  80. /*Static method@generated novel file can be called directly */
  81. ////////////////////////////////////////////////// ////////////////////////////////////////////////////// /////////
  82. public static function createBookById($id){
  83. if(!is_numeric($id)){
  84. echo "
    INIT BEGIN START WRITE!";
  85. $ st=new self();
  86. $cons=$st->getBookContextById($id);
  87. $title=$st->getBookNameById($id);
  88. $cons=trim($cons);
  89. $t =explode(" ",$title);
  90. //Construct directory
  91. $dir=array();
  92. $dir=explode("_",$t[0]);
  93. $wzdir=$dir[0]; //Book name as directory name
  94. $wzchapter=$dir[1]; //Chapter
  95. //Create directory
  96. $wzdir2=iconv("UTF-8", "GBK", $wzdir); //Directory When encoding, please note that the reference to the $wzdir string is retained here, which is used to construct the file name. It cannot be used here to prevent secondary encoding
  97. if(!file_exists($wzdir2)){
  98. mkdir($wzdir2); //Create a directory
  99. }
  100. //Construct the file name
  101. $wztitle="./".$wzdir."/"."$t[0]".".txt";
  102. //Ensure that the saved file name is not garbled
  103. $wztitle=iconv ("UTF-8", "GBK", $wztitle);
  104. $f=fopen($wztitle,"w+");
  105. fwrite($f,$cons);
  106. echo "$wzdir ".$wzchapter."Write successfully";
  107. fclose($f);
  108. }
  109. else{
  110. $ ids=self::getBookIdsById($id);
  111. //The server may be offline here, so it is best to use session recording loop
  112. #for($i=$_SESSION["$id"."_fid"];$ i<=count($ids);$_SESSION["$id"."_fid"]++,$i++){
  113. #self::createBookById($id."_".$ids[$_SESSION[" $id"."_fid"]++]);//Construct id
  114. #}
  115. for($i=$_SESSION["$id"."_fid"];$i<=count($ids); $_SESSION["$id"."_fid"]++,$i++){
  116. self::createBookById($id."_".$ids[$i]);//Construct id
  117. }
  118. # echo "


    The writing work is completed

    ";
  119. #echo $id."_".$ids[0 ]."
    ";
  120. #var_dump($ids);
  121. }
  122. }
  123. /*
  124. Get all the IDs of the novel
  125. @param $id article ID
  126. @return array;
  127. */
  128. public static function getBookIdsById($aid){
  129. $ch= curl_init();
  130. $url='http://www.motie.com/book/'.$aid."/chapter";
  131. //Note here ?The minimum matching items can be obtained
  132. $ru='/[sS]*?
  133. [sS]*?.*?. *?/u';//Regular expression matching
  134. //Set options, including URL
  135. curl_setopt($ch, CURLOPT_URL, $url);
  136. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//Do not automatically output content
  137. curl_setopt($ch, CURLOPT_HEADER, 0); //Does not return header information
  138. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 0);
  139. //Execute curl
  140. $output = curl_exec($ch);
  141. // Check if there are any errors Occurs
  142. if(curl_errno($ch)){
  143. echo 'Curl error: ' . curl_error($ch);
  144. }
  145. //Release curl handle
  146. curl_close($ch);
  147. $arr=array();
  148. preg_match_all ($ru,$output,$arr,PREG_PATTERN_ORDER);
  149. return $arr[1];
  150. }
  151. }
  152. ?>
Copy code
  1. session_start();
  2. require_once("SpiderTools.class.php");
  3. if($_REQUEST["bid"]){
  4. if(is_numeric($_REQUEST["bid"]) ){
  5. SpiderTools::createBookById(trim($_REQUEST["bid"]));
  6. }
  7. else{
  8. echo "
    Please enter the correct article ID
    ";
  9. }
  10. }
  11. ?>
Copy code
  1. Download the novel
  2. Enter the ID number of the novel you want to see on the Motie Chinese website to download the novel

  3. < /form>
  • Copy code


    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

    JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

    Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

    Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

    How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

    Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

    Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

    The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

    How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

    How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

    Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

    Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

    How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

    How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

    See all articles