我正在抓取网站,到目前为止,用Goutte解析HTML没有问题。但是我需要从网站上检索JSON,由于cookie管理,我不想用file_get_contents()来实现它--这是行不通的。
我可以使用纯cURL,但在这种情况下,我只想使用Goutte,而不想使用任何其他库。
那么,有什么方法我只能通过Goutte解析文本,还是真的必须用好的旧方法来解析呢?
/* Sample Code */
$client = new Client();
$crawler = $client->request('foo');
$crawler = $crawler->filter('bar'); // of course not working谢谢。
发布于 2013-09-11 12:52:41
在Goutte库中进行了非常深入的搜索之后,我找到了一种方法,并想要分享。因为Goutte是一个非常强大的库,但是有如此复杂的文档。
通过(Goutte >)解析JSON
只需获取所需的输出页面并将json存储到数组中即可。
$client = new Client(); // Goutte Client
$request = $client->getClient()->createRequest('GET', 'http://***.json');
/* getClient() for taking Guzzle Client */
$response = $request->send(); // Send created request to server
$data = $response->json(); // Returns PHP Array通过(Goutte + Guzzle)解析JSON和Cookies -用于身份验证
发送请求站点的一个页面(主页看起来更好)以获得cookie,然后使用这些cookie进行身份验证。
$client = new Client(); // Goutte Client
$crawler = $client->request("GET", "http://foo.bar");
/* Send request directly and get whole data. It includes cookies from server and
it automatically stored in Goutte Client object */
$request = $client->getClient()->createRequest('GET', 'http://foo.bar/baz.json');
/* getClient() for taking Guzzle Client */
$cookies = $client->getRequest()->getCookies();
foreach ($cookies as $key => $value) {
$request->addCookie($key, $value);
}
/* Get cookies from Goutte Client and add to cookies in Guzzle request */
$response = $request->send(); // Send created request to server
$data = $response->json(); // Returns PHP Array希望能帮上忙。因为我几乎花了3天时间来理解Gouttle和它的组成部分。
发布于 2015-03-31 00:52:32
经过几个小时的搜索,我发现了这一点,只需这样做:
$client = new Client(); // Goutte Client
$crawler = $client->request("GET", "http://foo.bar");
$jsonData = $crawler->text();发布于 2014-09-19 20:52:46
的解决方案对我没有用。我创建了一个新类"BetterClient":
use Goutte\Client as GoutteClient;
class BetterClient extends GoutteClient
{
private $guzzleResponse;
public function getGuzzleResponse() {
return $this->guzzleResponse;
}
protected function createResponse($response)
{
$this->guzzleResponse = $response;
return parent::createResponse($response);
}
}用法:
$client = new BetterClient();
$request = $client->request('GET', $url);
$data = $client->getGuzzleResponse()->json();https://stackoverflow.com/questions/18722528
复制相似问题