Очистить веб-страницу для набора данных - PullRequest
0 голосов
/ 09 ноября 2018

Я пытаюсь очистить содержимое веб-страницы, чтобы проверить, Набор данных Stata существует.

Я собрал несколько строк кода, но они не работают:

tempfile page
copy "https://www.stata-press.com/data/r15/u.html" "`page'"
tempname fh
file open `fh' using "`page'", read
file read `fh' line
while r(eof)==0 {
if "`line'"=="regsmpl.dta" dis "Dataset exists"
else dis "Dataset doesn't exit"
file read `fh' line
}
file close `fh'

Любые идеи будут высоко оценены.

1 Ответ

0 голосов
/ 09 ноября 2018

Вы можете сначала передать всю страницу в скалярную переменную, используя функцию fileread():

local dataset regsmpl
scalar page = fileread("https://www.stata-press.com/data/r15/u.html")

После того, как скаляр успешно создан, вы можете сделать это, используя два подхода.

Решение 1. Проверьте, упоминается ли набор данных на странице

if strmatch(page, "*`dataset'.dta*") display "Page mentions dataset"
else display "No trace of dataset in page"

Решение 2. Проверьте, существует ли фактическая ссылка, указывающая на набор данных

local link = ustrregexm(page, `"<a [^>]*\bhref\s*=\s*"([^"]*`dataset'.dta[^"]*)"')
local url =  trim(ustrregexs(1))

if "`url'" != "" display "The link is: `url'"
else display "There is no such link"

Ваш подход также может работать с регулярными выражениями strmatch() и :

tempname fh
file open `fh' using "https://www.stata-press.com/data/r15/u.html", read
file read `fh' line

local tag = 0
while r(eof) == 0 {
    if strmatch(`"`line'"', "*regsmpl.dta*") local tag = 1
    file read `fh' line
}

if `tag' == 1 display "Dataset exists"
else display "Dataset doesn't exit" 

tempname fh
file open `fh' using "https://www.stata-press.com/data/r15/u.html", read
file read `fh' line

local tag = 0
while r(eof) == 0 {
    local link = ustrregexm(`"`line'"', `"<a [^>]*\bhref\s*=\s*"([^"]*`dataset'.dta[^"]*)"')
    if `link' == 1 {
        local url = trim(ustrregexs(1))
        local tag = 1
    }
    file read `fh' line
}

if `tag' == 1 display "The link is: `url'"
else display "There is no such link"
...