Web Scraping в R с циклом из data.frame Rvest - PullRequest
0 голосов
/ 01 мая 2018

Итак, у меня есть список URL, которые я хотел бы просмотреть в R Studio

URL <- </p>

"https://www.ebay.in/sch/i.html?_nkw=Mobile+Phones&_pgn=2&_skc=2&_skc=200&rt=nc"
............
"https://www.ebay.in/sch/i.html?_nkw=Mobile+Phones&_pgn=2&_skc=10&_skc=1800&rt=nc"

У меня есть код, который может очистить список, когда в списке есть один URL:

library(rvest)
library(stringr)

# specify the url
url <-"https://www.ebay.in/sch/i.html?_nkw=Mobile+Phones&_pgn=2&_skc=2&_skc=200&rt=ncs"

# read the page
web <- read_html(url)

# define the supernode that has the entire block of information
super_node <- '.li' 

# read as vector of all blocks of supernode (imp: use html_nodes function)
super_node_read <- html_nodes(web, super_node)

# define each node element that you want
node_model_details <- '.lvtitle'
node_description_1 <- '.lvtitle+ .lvsubtitle'
node_description_2 <- '.lvsubtitle+ .lvsubtitle'
node_model_price   <- '.prc .bold'
node_shipping_info <- '.bfsp'
# extract the output for each as cleaned text (imp: use html_node function)
model_details <- html_node(super_node_read, node_model_details) %>%
html_text() %>%
str_replace_all("[\t\n\r]" , "")

description_1 <- html_node(super_node_read, node_description_1) %>%
html_text() %>%
str_replace_all("[\t\n\r]" , "")

description_2 <- html_node(super_node_read, node_description_2) %>%
html_text() %>%
str_replace_all("[\t\n\r]" , "")

model_price  <- html_node(super_node_read, node_model_price) %>%
html_text() %>%
str_replace_all("[\t\n\r]" , "")

shipping_info <- html_node(super_node_read, node_shipping_info) %>%
html_text() %>%
str_replace_all("[\t\n\r]" , "")

# create the data.frame
mobile_phone_data <- data.frame(
    model_details,
    description_1,
    description_2,
    model_price,
    shipping_info
)

Однако при добавлении нескольких URL в мой список URL я сталкиваюсь с приведенной ниже ошибкой с самого начала. Как я могу создать функцию цикла, чтобы я мог очистить несколько URL-адресов?

web <- read_html(url)
Error in doc_parse_file(con, encoding = encoding, as_html = as_html, options = options) : 
  Expecting a single string value: [type=character; extent=9].

1 Ответ

0 голосов
/ 01 мая 2018

Циклы могут не понадобиться, вы можете добиться всего этого в векторизованном виде. Некоторые из ваших узлов не работали, поэтому я заменил их на те, которые работали. Я также превратил ваш код в набор из двух функций.

library(dplyr)
library(tidyr)
library(tibble)
library(rvest)
library(stringr)
library(purrr)

extract_node <- function(node){
  # function that accepts a css selector or xpath to extract
  # text from an html node with
  super_node_read %>% 
      html_nodes(node) %>% 
      html_text()
}

extract_phone_details <- function(url){

  # read the page
  web <- read_html(url)

  # define the supernode that has the entire block of information
  super_node <- '.li' 

  # read as vector of all blocks of supernode (imp: use html_nodes function)
  super_node_read <- html_nodes(web, super_node)

  # define each node element that you want
  node_model_details <- '.lvtitle'
  node_model_price   <- '.prc'
  node_shipping_info <- 'li.lvshipping >span'

  # create the tibble
  mobile_phone_data <- tibble(
    model_details = extract_node(node_model_details),
    model_price = extract_node(node_model_price),
    shipping_info = extract_node(node_shipping_info))

  return(mobile_phone_data)
}

# using the function on a single url
url <-"https://www.ebay.in/sch/i.html?_nkw=Mobile+Phones&_pgn=2&_skc=2&_skc=200&rt=ncs"

df <- extract_phone_details(url)

# now you can apply this same function on any number of urls by using purrr's map function
# and tidyr's unnest
urls <- c("https://www.ebay.in/sch/i.html?_nkw=Mobile+Phones&_pgn=2&_skc=2&_skc=200&rt=nc",
          "https://www.ebay.in/sch/i.html?_nkw=Mobile+Phones&_pgn=2&_skc=10&_skc=1800&rt=nc")

df <- tibble(url = urls,
             results = map(url, extract_phone_details)) %>% 
  unnest
...