[問題] 網路爬蟲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