作者CruxLaelaps (唷咪)
看板R_Language
标题[问题] 爬虫,因为壅塞想让程式等待(已解决)
时间Fri Mar 19 18:36:35 2021
[软体熟悉度]:
使用者(已经有用R 做过不少作品)
[问题叙述]:
资料库网站本身载入就不快,有时更会塞车,读取网站的档案或路径时,
回传读取的连结(档案或路径)list,即便网站路径存在还是会读不到。
网站读取如果快的时候可以完成,请见范例程式。
如果慢的时候,就算连结存在,会出现错误,当下我开网页大约需要4分钟。
程式约3秒出现错误讯息。错误讯息为:
Error in open.connection(x, "rb") : cannot open the connection。
因为希望程式能自动每日执行,不会卡在有时因网站loading慢而中止,有甚麽方式
可以让程式等待网站呢?
[程式范例]:
成功的:
"
http://tisvcloud.freeway.gov.tw/history/" %>>% (~ cat('Now the program is at
', ., "\n")) %>>%
read_html("UTF8") %>>% xml_find_all("//*[@id='form1']//table/tbody") %>>%
xml_find_all("//tr/td[1]/a") %>>% xml_text %>>%
when(identical(.Platform$OS.type, "windows") ~ stri_conv(., "UTF-8",
"Big5"), ~ .)
结果:
Now the program is at
http://tisvcloud.freeway.gov.tw/history/
[1] "Parent Directory" "vd"
"TDCS_PINGLIN" "TDCS"
[5] "roadlevel" "motc20" "map"
...
[25] "1min_incident_data_1968.xml" "1968_incident.pdf"
--
失败的:
"
http://tisvcloud.freeway.gov.tw/history/TDCS/M08A/" %>>% (~ cat('Now the
program is at ', ., "\n")) %>>%
read_html("UTF8") %>>% xml_find_all("//*[@id='form1']//table/tbody") %>>%
xml_find_all("//tr/td[1]/a") %>>% xml_text %>>%
when(identical(.Platform$OS.type, "windows") ~ stri_conv(., "UTF-8",
"Big5"), ~ .)
结果:
Now the program is at
http://tisvcloud.freeway.gov.tw/history/TDCS/M08A/
Error in open.connection(x, "rb") : cannot open the connection
[环境叙述]:
WIN 10
R 4.0.4
[关键字]:
爬虫;网站壅塞
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 124.109.113.253 (台湾)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/R_Language/M.1616150204.A.551.html
1F:→ andrew43: read_html(..., options = "RECOVER") 有用吗? 03/19 22:51
2F:→ CruxLaelaps: 不行,结果一样 03/20 00:18
3F:→ showfeb: 用try(...)包住语法, 回圈遇错重覆执行. 03/20 00:48
我贴上的程式本来就被try()包住,又加上repeat包住,重复做,只是结果会有错误讯息的无穷回圈...网路实在太卡
--
4F:推 locka: 把read_html的结果存成一个变数,用if判断有抓到东西才做後 03/20 01:21
5F:推 locka: 续解析 03/20 01:21
6F:推 cywhale: 如果是这样的话,用 future(read_html) 再解析value()? 03/20 08:35
是用这位学长提的的方法解决,套件"httr"内的函数GET()设timeout
感谢这位学长!
--
8F:→ celestialgod: 或是三楼建议那样 可能比较好 03/20 14:32
9F:→ celestialgod: 这段code看起来是我5年前为某老师写的... 03/20 14:33
11F:→ celestialgod: 没想到会在R板看到自己写的东西XDDD 03/20 14:34
※ 编辑: CruxLaelaps (124.109.113.253 台湾), 03/25/2021 15:59:46