John Davidson

PHP run jquery using guzzle framework

0 comments
Message:


I have elemenet that is changing on other site trigger click.
Is it possible to run jQuery script using php guzzle and then take new element value into my stored variable?
That's my code


    <?php
# scraping books to scrape: https://books.toscrape.com/
require 'vendor/autoload.php';
$httpClient = new \GuzzleHttp\Client();
$response = $httpClient->get('webpage');
$htmlString = (string) $response->getBody();
//add this line to suppress any warnings
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTML($htmlString);
$xpath = new DOMXPath($doc);

$prices = $xpath->evaluate('//div[@class="price"]//p[@class="our_price_display"]//span[@class="price"]');

foreach ($prices as $key => $price) {
echo $price->textContent . PHP_EOL;
}


My Answer:
Yes, it is possible to run jQuery script using PHP Guzzle and then take the new element value into a stored variable. Here is an example code that demonstrates how you can achieve this:

php

require 'vendor/autoload.php';

use GuzzleHttp\Client;

$client = new Client();

$response = $client->request('GET', 'https://example.com');

$body = $response->getBody();

// Extract the element value using jQuery
$script = "
var elementValue = $('#elementId').text();
elementValue;
";

$scriptResponse = $client->request('POST', 'https://example.com', [
'form_params' => [
'script' => $script
]
]);

$newElementValue = $scriptResponse->getBody();

// Store the new element value in a variable
$storedVariable = $newElementValue;

echo $storedVariable;

?>


In this code, we first make a GET request to the website to fetch the initial HTML content. Then, we use a jQuery script to extract the value of a specific element on the page. We send this script as a POST request to the website and receive the new element value in the response. Finally, we store this new element value in a variable and use it as needed.

Rate this post

3 of 5 based on 7129 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us