作者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/m.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