library(rvest)
library(tm)
## Loading required package: NLP
library(stringr)
# Scrape text and meta tags from a website
url <- "https://apnews.com/article/alaska-airlines-portland-oregon-emergency-landing-aab8ee1e594369ab48fa3ce60f3acdc6" # Replace with your URL
webpage <- read_html(url)
# Extracting main text
text <- html_text(html_nodes(webpage, "p")) # Adjust the selector as needed
# Extracting meta tags, focus on 'keywords' and 'description'
meta_keywords <- html_attr(html_nodes(webpage, xpath='//meta[@name="keywords"]'), 'content')
meta_description <- html_attr(html_nodes(webpage, xpath='//meta[@name="description"]'), 'content')
# Combine text and meta content
combined_text <- paste(text, meta_keywords, meta_description, sep=" ")
# Create a corpus and preprocess
corpus <- Corpus(VectorSource(combined_text))
corpus <- tm_map(corpus, content_transformer(tolower))
## Warning in tm_map.SimpleCorpus(corpus, content_transformer(tolower)):
## transformation drops documents
corpus <- tm_map(corpus, removePunctuation)
## Warning in tm_map.SimpleCorpus(corpus, removePunctuation): transformation drops
## documents
corpus <- tm_map(corpus, removeWords, stopwords("en"))
## Warning in tm_map.SimpleCorpus(corpus, removeWords, stopwords("en")):
## transformation drops documents
# Convert the corpus to a plain text vector
plain_text <- unlist(lapply(corpus, as.character))
# Define keywords and count occurrences
keywords <- c("airlines", "flown", "broken") # Replace with your keywords
counts <- sapply(keywords, function(k) sum(str_count(plain_text, k)))
counts
## airlines flown broken
## 137 1 0