ESP8266简单爬取baidu网页源码

/*
 *  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);
}
  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值