• Уважаемые посетители сайта esp8266.ru!
    Мы отказались от размещения рекламы на страницах форума для большего комфорта пользователей.
    Вы можете оказать посильную поддержку администрации форума. Данные средства пойдут на оплату услуг облачных провайдеров для сайта esp8266.ru
  • Система автоматизации с открытым исходным кодом на базе esp8266/esp32 микроконтроллеров и приложения IoT Manager. Наша группа в Telegram

Парсер информации с сайта

BPOH

New member
Здравствуйте подскажите пожалуйста возможно ли парсить и выводить на экран ssd1306 информацию с сайта допустим новые видео на ютуб канале
 

tretyakov_sa

Moderator
Команда форума
Здравствуйте подскажите пожалуйста возможно ли парсить и выводить на экран ssd1306 информацию с сайта допустим новые видео на ютуб канале
 

BPOH

New member
Да это я для примера... интересует без API просто текст парсить
 

BPOH

New member
Получай на текст и парси.

C++:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h> // http web access library
#include <ArduinoJson.h> // JSON decoding library
// Libraries for SSD1306 OLED display
#include <Wire.h> // include wire library (for I2C devices such as the SSD1306 display)
#include <Adafruit_GFX.h> // include Adafruit graphics library
#include <Adafruit_SSD1306.h> // include Adafruit SSD1306 OLED display driver
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET LED_BUILTIN
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
const char* ssid = "wifi";
const char* password = "123321";
// set location and API key
//String Location = "City Name, Country Code";
//String API_Key = "Your API Key";
String Location = "London";
String API_Key = "1f7fb68c";

void setup(void)
{
Serial.begin(9600);
delay(1000);
//Wire.begin(4, 0); // set I2C pins [SDA = GPIO4 (D2), SCL = GPIO0 (D3)], default clock is 100kHz
// by default, we'll generate the high voltage from the 3.3v line internally! (neat!)
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // initialize with the I2C addr 0x3D (for the 128x64)
// init done
Wire.setClock(400000); // set I2C clock to 400kHz
display.clearDisplay(); // clear the display buffer
display.setTextColor(WHITE, BLACK);
display.setTextSize(1);
display.setCursor(0, 0);
display.println(utf8rus("   [Погода в Керчи]"));
display.print(utf8rus(" Статус - подключено"));
display.display();
WiFi.begin(ssid, password);
Serial.print("Connecting.");
display.setCursor(0, 24);
display.println(utf8rus("Подключаемся... "));
display.display();
while ( WiFi.status() != WL_CONNECTED )
{
delay(500);
Serial.print(".");
}
Serial.println("connected");
display.print("connected");
display.display();
delay(1000);
}
void loop()
{
if (WiFi.status() == WL_CONNECTED) //Check WiFi connection status
{
HTTPClient http; //Declare an object of class HTTPClient
// specify request destination
http.begin("http://api.openweathermap.org/data/2.5/weather?q=" + Location + "&APPID=" + API_Key); // !!
int httpCode = http.GET(); // send the request
if (httpCode > 0) // check the returning code
{
String payload = http.getString(); //Get the request response payload
DynamicJsonBuffer jsonBuffer(512);
// Parse JSON object
JsonObject& root = jsonBuffer.parseObject(payload);
if (!root.success()) {
Serial.println(F("Parsing failed!"));
return;
}
float temp = (float)(root["main"]["temp"]) - 273.15; // get temperature in °C
//int temp = root["main"]["temp"]; // get temperature in °C
int humidity = root["main"]["humidity"]; // get humidity in %
float pressure = (float)(root["main"]["pressure"]) / 1000; // get pressure in bar
float wind_speed = root["wind"]["speed"]; // get wind speed in m/s
int wind_degree = root["wind"]["deg"]; // get wind degree in °
// print data
Serial.printf("Temperature = %.2f°C\r\n", temp);
Serial.printf("Humidity = %d %%\r\n", humidity);
Serial.printf("Pressure = %.3f bar\r\n", pressure);
Serial.printf("Wind speed = %.1f m/s\r\n", wind_speed);
Serial.printf("Wind degree = %d°\r\n\r\n", wind_degree);
display.setCursor(0, 24);
display.printf("Temperature: %5.2f C\r\n", temp);
//display.printf("Temperature: %d C\r\n", temp);
display.printf("Humidity : %d %%\r\n", humidity);
display.printf("Pressure : %.3fbar\r\n", pressure);
display.printf("Wind speed : %.1f m/s\r\n", wind_speed);
display.printf("Wind degree: %d", wind_degree);
display.drawRect(109, 24, 3, 3, WHITE); // put degree symbol ( ° )
display.drawRect(97, 56, 3, 3, WHITE);
display.display();
}
http.end(); //Close connection
}
delay(20000); // wait 1 minute
}
// End of code.

/* Recode russian fonts from UTF-8 to Windows-1251 */
String utf8rus(String source)
{
  int i,k;
  String target;
  unsigned char n;
  char m[2] = { '0', '\0' };
 
  k = source.length(); i = 0;
 
  while (i < k) {
    n = source[i]; i++;
 
    if (n >= 0xBF){
      switch (n) {
        case 0xD0: {
          n = source[i]; i++;
          if (n == 0x81) { n = 0xA8; break; }
          if (n >= 0x90 && n <= 0xBF) n = n + 0x2F;
          break;
        }
        case 0xD1: {
          n = source[i]; i++;
          if (n == 0x91) { n = 0xB7; break; }
          if (n >= 0x80 && n <= 0x8F) n = n + 0x6F;
          break;
        }
      }
    }
    m[0] = n; target = target + String(m);
  }
return target;
}
Старинушка подскажи пожалуйста хоть пару строк парсинга для примера чтоб отталкиваться по образу и подобию, сейчас этот код погоду парсит всё работает, хочу пару строк отдать под парсер текста в поисковике не смог найти
 

tretyakov_sa

Moderator
Команда форума
Так формат текста какой? Образец нужен и что вытягивать?
 

BPOH

New member
С веб страницы зачем она огромная, проще через json
http://api.bitcoincharts.com/v1/markets.json на пример или аналогичную.
Вы можете пример кода рабочего дать? чтоб с моим скриптом подружилось? я так досихпор и не понял как html парсить, заранее примного благодарен
 
Сверху Снизу