Scrape Magento网站,该网站使用Cookie进行“添加到购物车”


Scrape Magento website which uses Cookies for "Add to cart"

我正在抓取这个网址。

我想刮掉这个项目的数量。

为此,我的策略是我将尝试添加数量并发布表单,直到出现错误,指出"xyz 产品"所需的数量不够。

我尝试使用file_get_contents();发布 FORM 并echo输出,它返回一个错误页面,指出Cookies must be enabled in your browser

这是我的发布方式

    $postdata = http_build_query(
            array(
                'product' => $prod_id,
                'qty' => 5,
                'related_product' => ''
            )
    );
    $opts = array('http' =>
        array(
            'method' => 'POST',
            'header' => 'Content-type: application/x-www-form-urlencoded',
            'content' => $postdata
        )
    );
    $context = stream_context_create($opts);
    $result = file_get_contents($action_url, false, $context);

我也尝试过cURL

$cookieFile = tempnam(空,"短信"); $userAgent = 'Mozilla/5.0 (X11;乌班图;Linux x86_64;rv:11.0) 壁虎/20100101火狐/11.0';

    $cookieFile = tempnam(null, 'SMS');
    $userAgent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:11.0) Gecko/20100101 Firefox/11.0';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $action_url);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
    curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 0);
    $post = array(
        'product' => $prod_id,
        'qty' => 5,
        'related_product' => '');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
    $html = curl_exec($ch);

但是我仍然从该站点收到错误,即应在浏览器中启用Cookie。

所以我的问题是如何使用 PHP 将产品添加到购物车?

我终于用Guzzle Goutte做到

无论服务器发送什么,它都会接收cookie。