[問題] 網路爬蟲cookie設定

看板R_Language作者 (money)時間7年前 (2018/01/02 14:37), 7年前編輯推噓1(109)
留言10則, 2人參與, 7年前最新討論串1/1
[問題類型]: 程式諮詢(我想用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 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 163.26.178.75 ※ 文章網址: https://www.ptt.cc/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

01/02 22:45, 7年前 , 1F
用regionid=15 or 1 not region 比如 xd<-GET("https://
01/02 22:45, 1F

01/02 22:46, 7年前 , 2F
rent.591.com.tw/home/search/rsList", query=list(
01/02 22:46, 2F

01/02 22:46, 7年前 , 3F
regionid=15)); fromJSON(content(xd, "text"))
01/02 22:46, 3F

01/02 22:47, 7年前 , 4F
可以得到台南的資料 改成regionid=1 得到台北
01/02 22:47, 4F

01/03 09:22, 7年前 , 5F
謝謝你,可以更改縣市了!
01/03 09:22, 5F

01/03 12:57, 7年前 , 6F
有人知道為什麼更改cookie沒辦法得到正確的縣市嗎?
01/03 12:57, 6F

01/03 23:43, 7年前 , 7F
你把你程式中的url region 都改成regionid去抓就會是對的
01/03 23:43, 7F

01/03 23:45, 7年前 , 8F
然後再用你程式碼 GET(url,set_cookies("urlJumpIp"="15"
01/03 23:45, 8F

01/04 00:34, 7年前 , 9F
我可能搞錯你問題的意思sorry set_cookies那邊我再想想><
01/04 00:34, 9F

01/04 12:29, 7年前 , 10F
不會,還是謝謝你,至少能正確抓到縣市資料
01/04 12:29, 10F
文章代碼(AID): #1QIoYXES (R_Language)
文章代碼(AID): #1QIoYXES (R_Language)