我正在嘗試運行一個腳本,該腳本將使用查詢字串搜索 Healthline 并確定是否有任何搜索結果,但我無法通過發布到頁面的查詢字串獲取內容。要在他們的網站上搜索某些內容,請轉到https://www.healthline.com/search?q1=search string。
這是我嘗試過的:
$healthline_url = 'https://www.healthline.com/search';
$search_string = 'ashwaganda';
$postdata = http_build_query(
array(
'q1' => $search_string
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$stream = stream_context_create($opts);
$theHtmlToParse = file_get_contents($healthline_url, false, $stream);
print_r($theHtmlToParse);
我還嘗試將查詢字串添加到 url 并跳過流,以及其他變體,但我已經沒有想法了。這也不起作用:
$healthline_url = 'https://www.healthline.com/search';
$search_string = 'ashwaganda';
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Content-Type: text/xml; charset=utf-8"
)
);
$stream = stream_context_create($opts);
$theHtmlToParse = file_get_contents($healthline_url.'&q1='.$search_string, false, $stream);
print_r($theHtmlToParse);
和建議?
編輯:我更改了 url,以防有人想查看搜索頁面。還修復了查詢字串。還是不行。
為了回應 Ken Lee,我確實嘗試了以下 cURL 腳本,該腳本也只回傳沒有搜索結果的頁面:
$healthline_url = 'https://www.healthline.com/search?q1=ashwaganda';
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $healthline_url);
$data = curl_exec($ch);
curl_close($ch);
print_r($data);
uj5u.com熱心網友回復:
Healthline 不會直接加載搜索結果。它的搜索索引存盤在Algolia 中,并進行了額外的 javascript 呼叫來檢索結果。因此,您無法通過 看到搜索結果file_get_content。
要查看搜索結果,您需要運行一個瀏覽器模擬器來模擬支持 javascript 的瀏覽器以正確運行站點頁面。
PHP開發者可以嘗試使用php-webdriver通過webdriver控制瀏覽器(例如Selenium、Chrome chromedriver、Firefox geckodriver)。
更新:不知道目標站點是 Healthline。我發現后更新了答案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/353823.html
