[问题] 网络爬虫cookie设定

楼主: eri820503 (snoopyahoo)   2018-01-02 14:37:13
[问题类型]:
程式咨询(我想用R 做某件事情,但是我不知道要怎么用R 写出来)
[软件熟悉度]:
使用者(已经有用R 做过不少作品)
[问题叙述]:
我想用R做网络爬虫,透过设定不同的cookie爬资料,
我用591租屋网("https://rent.591.com.tw/new/?kind=0&region=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
作者: cywhale (cywhale)   2018-01-02 22:45:00
用regionid=15 or 1 not region 比如 xd<-GET("https://rent.591.com.tw/home/search/rsList", query=list(regionid=15)); fromJSON(content(xd, "text"))可以得到台南的资料 改成regionid=1 得到台北
楼主: eri820503 (snoopyahoo)   2018-01-03 09:22:00
谢谢你,可以更改县市了!有人知道为什么更改cookie没办法得到正确的县市吗?
作者: cywhale (cywhale)   2018-01-03 23:43:00
你把你程式中的url region 都改成regionid去抓就会是对的然后再用你程式码 GET(url,set_cookies("urlJumpIp"="15"我可能搞错你问题的意思sorry set_cookies那边我再想想><
楼主: eri820503 (snoopyahoo)   2018-01-04 12:29:00
不会,还是谢谢你,至少能正确抓到县市资料

Links booklink

Contact Us: admin [ a t ] ucptt.com