编译数据,当网页抓取时缺少值时该怎么办?

时间:2018-05-23 23:28:49

标签: r database web-scraping

我有几个问题。

我正在从日志中抓取数据并尝试将其编译成数据集。我编译时遇到的问题是我正在抓取的一些html对象的空值。

page1<-read_html("http://journals.sagepub.com/doi/full/10.3102/0013189X08317501")
author <- html_text(html_nodes(page1, '.art_authors'))
year <- html_text(html_nodes(page1, '.year'))
journalName <- html_text(html_nodes(page1, '.journalName'))
art_title <- html_text(html_nodes(page1, '.art_title'))
volume <- html_text(html_nodes(page1, '.volume'))
page <- html_text(html_nodes(page1, '.page'))
email <- html_text(html_nodes(page1, xpath = "//a[@class = 'email']"))
row1<-cbind(author, year, journalName, art_title, volume, page, email)

page2<-read_html("http://journals.sagepub.com/doi/abs/10.3102/0013189X037002102")
author <- html_text(html_nodes(page2, '.art_authors'))
year <- html_text(html_nodes(page2, '.year'))
journalName <- html_text(html_nodes(page2, '.journalName'))
art_title <- html_text(html_nodes(page2, '.art_title'))
volume <- html_text(html_nodes(page2, '.volume'))
page <- html_text(html_nodes(page2, '.page'))
email <- html_text(html_nodes(page2, xpath = "//a[@class = 'email']"))
row2<-cbind(author, year, journalName, art_title, volume, page, email)

page3<-read_html("http://journals.sagepub.com/doi/abs/10.3102/0013189X037002104")
author <- html_text(html_nodes(page3, '.art_authors'))
year <- html_text(html_nodes(page3, '.year'))
journalName <- html_text(html_nodes(page3, '.journalName'))
art_title <- html_text(html_nodes(page3, '.art_title'))
volume <- html_text(html_nodes(page3, '.volume'))
page <- html_text(html_nodes(page3, '.page'))
email <- html_text(html_nodes(page3, xpath = "//a[@class = 'email']"))
row3<-cbind(author, year, journalName, art_title, volume, page, email)
View (row3)

a <- rbind (row1, row2, row3)

所以这就成了一个问题,因为第三篇文章遗漏了他们的电子邮件。

我有另一个问题,我有一个包含所有

的列表
pagex<-read_html("http://journals.sagepub.com/doi/full/xxxx/xxxxxxx")

准备实施。但是我必须有一个更好的方法,而不是手动更改每个条目的所有代码行,因为顺序是顺序的。我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

对于问题的第一部分,您可以为每个抓取节点编写if-else条件,以便在缺少字段时指定默认值。

此外,您可以将所有网址保存在列表中,并将列表的长度循环显示,并将其保存到循环内的数据框中,而不是单独调用这三个页面。