ESP8266简单爬取baidu网页源码

一笑奈何 提交于 2020-01-30 07:58:09
/*
 *  This sketch demonstrates how to set up a simple HTTP-like server.
 *  The server will set a GPIO pin depending on the request
 *    http://server_ip/gpio/0 will set the GPIO2 low,
 *    http://server_ip/gpio/1 will set the GPIO2 high
 *  server_ip is the IP address of the ESP8266 module, will be 
 *  printed to Serial when the module is connected.
 */

#include <ESP8266WiFi.h>

const char* ssid = "MERCURY_5038";//wifi名称
const char* password = "00001111";//wifi密码
const char* host="www.baidu.com";

WiFiServer server(80);//开启80端口

void setup() {
  Serial.begin(115200);//开启串口监视器
  delay(10);

  // prepare GPIO2
  pinMode(2, OUTPUT);//设置2号(D4)输出
  digitalWrite(2, 0);//默认low
  
  // Connect to WiFi network
  Serial.print("Connecting to");
  Serial.println(ssid);
  
  WiFi.begin(ssid, password);//使用名称和密码链接wifi
  
  while (WiFi.status() != WL_CONNECTED) {//如果连接成功跳出循环
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  
  // Start the server
  server.begin();//开启服务器
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());//输出板子的ip
}

int value=0;
void loop() {
  // put your main code here, to run repeatedly:
  Serial.print("Connecting to");
  Serial.println(host);
  WiFiClient client;//tcp连接
  const int httpPort=80;//端口号
  if(!client.connect(host,httpPort)){//连接失败
    Serial.println("connection failed");
    return;
  }
  //向服务器发送请求
  client.print(String("GET /")+" HTTP/1.1\r\n"+
"Host: "+host+"\r\n"+"Connection: close\r\n\r\n");
  delay(50);

  //读取返回值
  while(client.available()){
    String line=client.readStringUntil('\r');
    Serial.print(line);
  }
  Serial.println();
  Serial.println("closing connection");
  delay(5000);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!