输入关键字 抓取所有网页(【每日一题】用rvest写了个抓取网站关键字搜索结果的脚本 )
优采云 发布时间: 2021-10-26 13:13输入关键字 抓取所有网页(【每日一题】用rvest写了个抓取网站关键字搜索结果的脚本
)
我很久没有使用 R 了。今天复习了一下,写了一个脚本,用rvest抓取网站关键字搜索结果。分享一下。
需求分析网站请求
打开网站,输入关键字疾病,就可以得到搜索链接,显然是GET请求
观察链接,可以看到q=disease是关键字,p=2是页码,pn=20是每页记录数,其他参数也可以试试
搜索列表抓取功能
<p>library("rvest")
getPageList % html_attr("href")
# 选择authors等标签内的文本, 并进行gsub处理掉其中的空格等多余字符
authors % html_text() %>% gsub(pattern=" {2,}|\n|\r", replacement="")
sources % html_text() %>% gsub(pattern="\r|\n *", replacement=" ")
pmid % html_text() %>% gsub(pattern="\r\n| ?|\u00A0",replacement="")
# 结果保存入dataframe并返回
iData % gsub(pattern="Abstract(\\n)*(\\t)*|\\n\\t*", replacement="")
# 有的页面没有摘要信息, 会返回 character(0) , 需要做个处理, 否则会报错
if (identical(tmp, character(0))){
tmp