iT邦幫忙

0

[php,curl]抓網頁內容出現錯誤

舜~ 2020-05-02 11:50:107191 瀏覽

前輩們問一下,我有一個需求是要取得指定網址的title

所以我透過CURL把該網址的html爬下再做後續處理

不過有一些網址會出現下面錯誤

  • Failed to connect to port 443: Connection refused
    www.shanhua.gov.tw
    commercial.tainan.gov.tw

  • Connection timed out after 20000 milliseconds
    ge.tainan.gov.tw
    我把CURLOPT_TIMEOUT調高到60,錯誤訊息變成
    Failed to connect to port 443: Timed out

  • error:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 unrecognized name
    61-216-49-197.hinet-ip.hinet.net

想問一下要如何解決這個問題?

下面是我抓網頁的code

$agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); // 要訪問的地址
curl_setopt($ch, CURLOPT_HTTPHEADER, ["application/json; charset=utf-8"]);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_HEADER, true); // 顯示返回的Header區域內容
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // 不要對認證證書來源的檢查
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  0); // 不要從證書中檢查SSL加密演算法是否存在
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET'); // 傳送一個常規的GET請求
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  // 獲取的資訊以檔案流的形式返回
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);  // 自動設定Referer
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 使用自動跳轉
curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate'); // 解釋gzip內容
curl_setopt($ch, CURLOPT_USERAGENT, $agent); // 模擬瀏覽器,有些網站沒這個會出現403錯誤
curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_DEFAULT); //SSL
// curl_setopt($ch, CURLOPT_NOBODY, true); // 不含網頁內容(只有標頭)
// curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); // 限制IPv4,沒成功避免Failed to connect to port 443: Connection refused

$r = curl_exec($ch);
if ($r === FALSE)
    $r = curl_error($ch);
return $r
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
通靈亡
iT邦高手 1 級 ‧ 2020-05-02 22:53:06
最佳解答

Failed to connect to port 443: Connection refused
www.shanhua.gov.tw
commercial.tainan.gov.tw

Connection timed out after 20000 milliseconds
ge.tainan.gov.tw
我把CURLOPT_TIMEOUT調高到60,錯誤訊息變成
Failed to connect to port 443: Timed out

error:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 unrecognized name
61-216-49-197.hinet-ip.hinet.net

由於你要存取的網站不支援Https
而你去存取它的 Https 443 port,導致無法連線

一般不支援Https的連線要連80 port
你把下面三行拿掉試試看

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // 不要對認證證書來源的檢查
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  0); // 不要從證書中檢查SSL加密演算法是否存在
curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_DEFAULT); //SSL
舜~ iT邦高手 1 級 ‧ 2020-05-02 23:08:56 檢舉

!! 沒注意到這個,感恩提醒,晚點來調整

我要發表回答

立即登入回答