代码之家  ›  专栏  ›  技术社区  ›  Maurice69

卷曲抓取给我“请求被拒绝”请求的URL被拒绝

  •  1
  • Maurice69  · 技术社区  · 7 年前

    我正在尝试使用以下代码获取网站的产品图像:

    <?php
    
    $url="http://www.akasa.com.tw/update.php?tpl=product/cpu.gallery.tpl&type=Fanless Chassis&type_sub=Fanless Mini ITX&model=A-ITX19-A1B";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_USERAGENT, "User-Agent: Mozilla/6.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.7) Gecko/20050414 Firefox/1.0.3");
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_ENCODING, "");
    $pagebody=curl_exec($ch);
    
    curl_close ($ch);
    
    $html=str_get_html($pagebody);
    
    print_r($html);
    

    PHPStorm让我读取变量,$pagebody得到这个值:

    <html><head><title>Request Rejected</title></head><body>The requested URL was rejected. If you think this is an error, please contact the webmaster. <br><br>Your support ID is: 4977197659118049932</body></html>
    

    http://www.akasa.com.tw/update.php?tpl=product/cpu.gallery.tpl&type=Fanless Chassis&type_sub=Fanless Mini ITX&model=A-ITX19-A1B

    当我使用浏览器时,我能很好地看到页面,pagesource也能提供我需要的所有信息,但我想自动从中抓取一些图像。你知道如何找出我需要用cURL发送什么信息,这样网站就不会把我当成机器人(我想这就是问题所在),或者如何找到解决这些问题的方法吗?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Flying    7 年前

    基本上,您需要对查询字符串参数进行编码,以便将所有特殊字符正确表示为url。您可以使用 http_build_query 为此,您的url结构可能如下所示:

    $url = implode('?', [
        'http://www.akasa.com.tw/update.php',
        http_build_query([
            'tpl'      => 'product/cpu.gallery.tpl',
            'type'     => 'Fanless Chassis',
            'type_sub' => 'Fanless Mini ITX',
            'model'    => 'A-ITX19-A1B',
        ])
    ]);
    

    然后是剩下的代码。