coderLMN / AutomatedDataCollectionWithR

《基于 R 语言的自动化数据采集技术》读者讨论区
28 stars 10 forks source link

教材P196,POST搭配url-encoded正文提交表单 #6

Closed dayushan closed 7 years ago

dayushan commented 7 years ago
url<-"http://read-able.com/"
info<-debugGatherer()
handle<-getCurlHandle(cookiejar     ="",
                followlocation=TRUE,
                autoreferer   =TRUE,
                debugfunc     =info$update,
                verbose       =TRUE,
                      httpheader    =list(from="wujinlan@lianjia.com",'user-agent'=str_c(R.version$version.string,",",R.version$platform))
)
xmlAttrsToDF<-function(parsedHTML,xpath){
    x<-xpathApply(parsedHTML,xpath,xmlAttrs)
    x<-lapply(x,function(x) as.data.frame(t(x)))
    do.call(rbind.fill,x)
}
html_form_res<-getURL(url=url,curl=handle)
form<-htmlParse(html_form_res)
xmlAttrsToDF(form,"//form")

xmlAttrsToDF(form,"//form[2]//input")
# 通过查看表单的完整源代码,我们发现有个textarea节点可以采集要发送给服务器的文本

xpathApply(form,"//form[2]")
## 这个textarea节点的name属性值是directInput,发送文本时它会作为参数名
# 用sentence来检验其可读性

sentence<-"\"It is a capital mistake to theorize before one has data. Insensibly one begins to twist facts to suit theories, instead of theories to suit facts.\"--Arthur Conan Doyle, Sherlock Holmes"
res<-postForm(uri=str_c(url,"check.php"),##加上了action属性值
          curl=handle,
          style="HTTPPOST",
          directInput=sentence
)
readHTMLTable(res)

当我输入上述代码时,R报错:

Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘readHTMLTable’ for signature ‘"raw"’

请问下是什么原因呢?错在哪?怎么解决?

coderLMN commented 7 years ago

手动提交了这段文字之后大致看了一下页面的结构,应该是网页改版了,返回的可读性分析结果并不包含 <table> 元素,而是一个 <div> 元素,所以 readHTMLTable() 函数找不到表格。

另外,我执行上面的 postForm() 函数好像得到的是一个报错的页面,你可以直接查看返回的 res 对象里面的内容核对一下,再去调整代码。

网页抓取的一个普遍问题就是网页会有经常性的改版,网页元素的结构、id 都有可能发生变化,导致抓取的程序也要随之经常更新。

dayushan commented 7 years ago

image image 确实是有

元素 我找到原因了,是因为url不对,虽然url<-"http://read-able.com/"会跳转到可读性分析网页,但在postForm()函数里uri=str_c(url,"check.php")其实是错的,正确的是url<-"http://www.webpagefx.com/tools/read-able/"