I am trying to do web scraping in dialogflow.
const rp = require('request-promise');
const ch = require('cheerio');
.
app.intent('get show name', (conv, {show_name}) => {
const url = 'https://screenrant.com/search/'+show_name;
rp(url).then(function(html){
let total_items = ch('article > div > h3 > a', html).length;
if(total_items > 0){
conv.ask(ch('article > div > h3 > a', html)[0].children[0].data);
}
else{
conv.ask("Sorry no news on this!");
}
});
});
This is my code. When running the action, I'm getting 'final_response' must be set.
This is an asynchronous command, so you need to return a Promise in your intent handler so the code knows to wait.
app.intent('get show name', (conv, {show_name}) => {
const url = 'https://screenrant.com/search/'+show_name;
return rp(url).then(function(html){
let total_items = ch('article > div > h3 > a', html).length;
if(total_items > 0){
conv.ask(ch('article > div > h3 > a', html)[0].children[0].data);
}
else{
conv.ask("Sorry no news on this!");
}
});
});
While you are doing web scraping in dialogflow. I will suggest using the in-built inline editor in it.
The same code be rewritten as
var request = require('request');
var cheerio = require('cheerio');
function welcome(agent) {
//agent.add(`Welcome to my agent!`);
var search_term = agent.parameters['term'];
st = urlencode(search_term);
request('https://screenrant.com/search/'+st+'/', function (error, response, html) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(html);
var responseText = "Here are the news";
$("article").each(function(){
responseText += "- " + $(this).find("h3").text();
})
agent.add(responseText)
}
});
}
To make it work, make sure the following:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.