作者eri820503 (money)
看板R_Language
标题[问题] 网路爬虫cookie设定
时间Tue Jan 2 14:37:13 2018
[问题类型]:
程式谘询(我想用R 做某件事情,但是我不知道要怎麽用R 写出来)
[软体熟悉度]:
使用者(已经有用R 做过不少作品)
[问题叙述]:
我想用R做网路爬虫,透过设定不同的cookie爬资料,
我用591租屋网("
https://rent.591.com.tw/new/?kind=0®ion=15")做练习,
不过不知道该如何在R设定cookie,使用的package为httr及rvest。
从chrome及Postman查到该网站的资料放在:
https://rent.591.com.tw/home/search/rsList?region=15&firstRow=0,
而我想更改不同的县市,从网址上来看是改region,
不过因为该网站是从cookie控制县市,cookie变数为"urlJumpIp",
但不知道该如何在R内修改。
参考网页:
https://ithelp.ithome.com.tw/articles/10191506
http://slides.com/andylin/deck-3#/
https://rpubs.com/jnwang/226877
[程式范例]:
library(jsonlite)
library(httr)
library(rvest)
#########从这两行code查出的资料皆为台南
d1=fromJSON("
https://rent.591.com.tw/home/search/rsList?region=1&firstRow=0")
d2=fromJSON("
https://rent.591.com.tw/home/search/rsList?region=15&firstRow=0")
d1$data$data$regionname
d2$data$data$regionname
#########所以透过rvest内的session去爬
url="
https://rent.591.com.tw/new"
session <- html_session(url,set_cookies("urlJumpIp=1"))
> session
<session>
https://rent.591.com.tw/new/
Status: 200
Type: text/html; charset=UTF-8
Size: 210222
#接着透过下面指令将资料抓出来,不过仍为台南的资料
session%>%
html_node("body")%>%
html_text(trim=TRUE)
#若把url改成
url="
https://rent.591.com.tw/home/search/rsList?region=1&firstRow=0"
session <- html_session(url,set_cookies("urlJumpIp=1"))
>session
<session>
https://rent.591.com.tw/home/search/rsList?region=1&firstRow=0
Status: 200
Type: application/json
Size: 98311
#但做到这里不知道该如何把json的资料抓出来
##############若透过httr的GET
url="
https://rent.591.com.tw/home/search/rsList?region=1&firstRow=0"
doc <- GET(url,set_cookies("urlJumpIp"="1"))
fromJSON(content(doc, "text"))
#爬出来的资料仍然是台南的
[关键字]:
webcrawling、rvest、httr、cookie
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 163.26.178.75
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/R_Language/M.1514875041.A.39C.html
※ 编辑: eri820503 (163.26.178.75), 01/02/2018 14:39:36
※ 编辑: eri820503 (163.26.178.75), 01/02/2018 14:45:10
1F:推 cywhale: 用regionid=15 or 1 not region 比如 xd<-GET("https:// 01/02 22:45
2F:→ cywhale: rent.591.com.tw/home/search/rsList", query=list( 01/02 22:46
3F:→ cywhale: regionid=15)); fromJSON(content(xd, "text")) 01/02 22:46
4F:→ cywhale: 可以得到台南的资料 改成regionid=1 得到台北 01/02 22:47
5F:→ eri820503: 谢谢你,可以更改县市了! 01/03 09:22
6F:→ eri820503: 有人知道为什麽更改cookie没办法得到正确的县市吗? 01/03 12:57
7F:→ cywhale: 你把你程式中的url region 都改成regionid去抓就会是对的 01/03 23:43
8F:→ cywhale: 然後再用你程式码 GET(url,set_cookies("urlJumpIp"="15" 01/03 23:45
9F:→ cywhale: 我可能搞错你问题的意思sorry set_cookies那边我再想想>< 01/04 00:34
10F:→ eri820503: 不会,还是谢谢你,至少能正确抓到县市资料 01/04 12:29