[英]how to build a webscraper in R using readLines and grep?
我是R的新手。我想編寫一份100萬字的報紙文章。 因此,我正在嘗試編寫一個網絡刮刀來檢索來自監護人網站的報紙文章: http : //www.guardian.co.uk/politics/2011/oct/31/nick-clegg-investment-new-jobs 。
刮刀用於從一頁開始,檢索文章的正文,刪除所有標簽並將其保存到文本文件中。 然后它應該通過本頁面上的鏈接轉到下一篇文章,獲取文章等,直到該文件包含大約100萬字。
不幸的是,我的刮刀並沒有走得太遠。
我使用readLines()來訪問網站的源代碼,現在想要獲取代碼中的相關行。
Guardian中的相關部分使用此ID來標記文章的正文:
<div id="article-body-blocks">
<p>
<a href="http://www.guardian.co.uk/politics/boris"
title="More from guardian.co.uk on Boris Johnson">Boris Johnson</a>,
the...a different approach."
</p>
</div>
我嘗試使用grep和lookbehind的各種表達式來掌握這一部分 - 嘗試獲取此ID后面的行 - 但我認為它不適用於多行。 至少我不能讓它發揮作用。
有人可以幫忙嗎? 如果有人可以提供一些我可以繼續工作的代碼,那將是很棒的!
謝謝。
如果您真的堅持使用grep
和readLines
,那么您將面臨清理已刪除頁面的問題,但這當然可以完成。 例如。:
加載頁面:
html <- readLines('http://www.guardian.co.uk/politics/2011/oct/31/nick-clegg-investment-new-jobs')
在stringr
包的str_extract
和簡單的正則表達式的幫助下,你完成了:
library(stringr)
body <- str_extract(paste(html, collapse='\n'), '<div id="article-body-blocks">.*</div>')
好吧, body
看起來很難看,你必須從<p>
和腳本中清理它。 這可以通過gsub
和朋友(很好的正則表達式)來完成。 例如:
gsub('<script(.*?)script>|<span(.*?)>|<div(.*?)>|</div>|</p>|<p(.*?)>|<a(.*?)>|\n|\t', '', body)
正如@Andrie建議的那樣,你應該使用一些為此目的構建的包。 小演示:
library(XML)
library(RCurl)
webpage <- getURL('http://www.guardian.co.uk/politics/2011/oct/31/nick-clegg-investment-new-jobs')
webpage <- readLines(tc <- textConnection(webpage)); close(tc)
pagetree <- htmlTreeParse(webpage, useInternalNodes = TRUE, encoding='UTF-8')
body <- xpathSApply(pagetree, "//div[@id='article-body-blocks']/p", xmlValue)
body
導致文本干凈的地方:
> str(body)
chr [1:33] "The deputy prime minister, Nick Clegg, has said the government's regional growth fund will provide a \"snowball effect that cre"| __truncated__ ...
更新 :以上作為單行(感謝@Martin Morgan的建議):
xpathSApply(htmlTreeParse('http://www.guardian.co.uk/politics/2011/oct/31/nick-clegg-investment-new-jobs', useInternalNodes = TRUE, encoding='UTF-8'), "//div[@id='article-body-blocks']/p", xmlValue)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.