Hello, dear Knimers,
I need to make a web scraping with COVID-19 financial data from a governmental Brazilian web portal (by the way, I and my research are Brazilian).
The source for the desired data is the URL Informações de Saúde (TABNET) – DATASUS; on this page, I have two interesting options, under “Assistência à Saúde” (or Health Assistance):
a) Produção Hospitalar (SIH/SUS) – DATASUS → for data from hospital admissions; and
b) Produção Ambulatorial (SIA/SUS) – DATASUS → for data from outpatient care;
And I need to compare both expenses monthly, along the period from Jan-2020 to May-2023. I wish to construct timelines for these value fluctuations.
I planned to use the Knime nodes “Webpage Retriever” and “XPath” at the beginning of my workflow. But I couldn’t configure adequately both nodes,
another option I should scrape is: besides for every month, I need to collect data for every city, and there are 497 municipalities in our State. The web scraping procedure would bring me a table for hospital admissions (subtotal financial amounts) with 497 lines (one for each city) and 41 columns (one for each month), and another similar table for outpatient care.
Can someone help me with this task?
Thanks in advance.
B.R.
Hello @rogerius1st ,
You are right if you plan to use the Webpage Retriever node and Xpath node.
Did you install the respective extension for these nodes?
Could you kindly share your workflow with us so we can better understand why the node configuration was unsuccessful?
Thank you,
Sanket
Dear @sanket_2012 ,
Thank you for all your help. And you were right, I hadn’t installed the Extensions, yet (though I’ve done it, now).
To explain myself (and my situation) a little better, I have to tell you that I do not know much about HTML, or XML, for I’m not a programmer. This way, I don’t know how to distinguish which code lines (I just searched for “href” code lines on the output results of the node XPath, but I couldn’t find out which one(s) should I choose).
I took the model for my workflow from Roberto_Cadili’s post, at https://hub.knime.com/roberto_cadili/spaces/Marketing%20Challenge%20KNIME%20&%20LUISS/latest/Basic%20Data%20Retrieval%20Examples~Aro574B1XPIbh_Nw.
My first steps for the ETL phase might look like this:
The first URL for my data sources is as follows:
A) TabNet Win32 3.0: Procedimentos hospitalares do SUS - por gestor - Rio Grande do Sul → For hospital financial amounts. There, I have three lists of available “options”, as in the image below:
(which means: "Hospital procedures - by the manager - in Rio Grande do Sul (my home State)).
For them, I selected the following respective “values”:
- on the line (or “Linha”), I set the value “Município Gestor” (or “name of the managing city”), for I want the total amount spent in each municipality;
- on the column (or “Coluna”), I set “Ano/Mês Processamento” (or Year/Month Processing), for I want the monthly period for subtotal expenses; and
- on the “Conteúdo” (or “Contents”), I selected “Valor Total” (or “Total amount”), for I want just the total sum of expenses for every city and every month of my research period.
Thus, my doubt about scraping lies in the next step: I need to collect raw data for every month AND every municipality, along a series of 40 months, generating a table with 498 lines (one line for each of the 497 cities of my home State (Rio Grande do Sul or “RS”), plus one line for the total amount), and 40 columns (for 40 months). To limit the interval of months from Jan-2020 to Apr-2023 (and not for the whole available dataset), I intend to use the “Column Filter” node in further steps.
Besides, there are two similar “Options” to set values: on the Option “Seleções disponíveis” (or “Available Selections”), I need to set successive values for “Caráter Atendimento” (or “Attendance Nature”): 1) “Eletivo” (or “Elective”); and 2) “Urgência” (or “Emergency”) p
+rocedures. Logically, if I select both of them simultaneously, I would have just the sum of these values, but not separately one or the other. And I desire an enhanced analysis, option by option, to analyze both factors individually. Thus, I think I should need to repeat this step twice, with both values.
My goal is to automate this scraping, instead of having to do it all again, manually, value by value, time after time.
And my second data source is as follows:
B) TabNet Win32 3.0: Produção Ambulatorial do SUS - por gestor - Rio Grande do Sul → For Outpatient (or “Ambulatorial”) financial amounts. Once again, I wish for the same analysis, both for Elective and Emergency procedures. In this step, I have similar lists of available “options”, as in the image below:
For these three values, I set similar values, except that on “Conteúdo” (or “Contents”), I set the value “Valor apresentado” (or “Executed value”). And the tasks are the same as before.
Did I help you for understanding my difficulty? I need to build a workflow to automate the generation of four distinct tables (to feed the further construction of four timelines) with financial data (the monthly subtotals) for:
- Hospital elective procedures;
- Hospital emergency procedures;
- Outpatient elective procedures; and
- Outpatient emergency procedures.
Thanks for your help (and comprehension). BTW, sorry if I am too detailed, or too time-consuming in my explanation, but I aimed to make myself clear enough.
Rogério.
Hi @rogerius1st ,
Apologies for the delayed reply.
I think you are on the right track regarding the first steps following @roberto_cadili’s workflow.
In addition to this, you might want to look at this blog post by @armingrudd that might help you further.
The blog post refers to the use of HTTPRetriever node, but you can use the WebPage Retriever and skip adding the namespaces which is instructed in the blog post.
Let me know if it works for you.
Thanks,
Sanket
Hi @rogerius1st , guys…
Rogerius, a página é um formulário e como tal, você seleciona opções e faz uma chamada para que os dados sejam lidos e processados. Como você comentou não ter muito conhecimento em programação, entendo que algumas definições seriam importantes para que você possa encurtar caminhos a este respeito.
A página em questão tem um código HTML na qual vou colocar a imagem aqui para ajudar a comunidade visualizar e colaborar com a solução ok?
Veja que deixei destacado a linha onde aparece o início do formulário e ele tem a indicação da página que vai receber as informações das seleções para a consulta.
Esta página seria “/cgi/tabcgi.exe?sih/cnv/qgrs.def” e o método de envio é “POST”.
Para requisições no navegador ou pelo HTTP Retrivier, você precisaria passar a URL completa como esta:
" TabNet Win32 3.0: Procedimentos hospitalares do SUS - por gestor - Rio Grande do Sul "
Tendo mais algumas informações (qual o campo ou onde definir a data, local e afins), você consegue criar um loop de requisições específicas e de melhor controle para obter as suas respostas.
No caso das caixas de seleção “Linha”, “Coluna” e “Conteúdo”, veja que possuem diferentes critérios, mas a indicação é específica:
No caso de “Linha”, ela tem o seletor/indicador chamado “L” e que o valor de “L” seria uma das opções destacadas abaixo, mas o que seria passado é o que está dentro do critério value=“XXXXX”
O mesmo ponto para os demais seletores.
L = Linha / C = Coluna / I = Conteúdo / A = Período e por ai vai… tem uma grande quantidade de campos pré-definidos, mas se precisar fazer um a um, recomendo que extraia com o xpath estes seletores e crie micro tabelas para cruzamento dentro do Knime.
Então:
L=Município_gestor
C=Ano/mês_processamento
I=Valor_total
A=qgrs2304.dbf
…
Hoje, existem algumas extensões que podem te ajudar além das presentes no knime que são da NodePit com o webpage content extractor ( https://nodepit.com/node/ws.palladian.nodes.extraction.content2.ContentExtractor2NodeFactory ) ou pelo Xpath para compor os dados para sua consulta.
Como seria feita uma consulta com dados passando pelo website, usaria o “POST Request” node, pois ele já é para requisitar no modelo POST, você pode efetuar requisições/chamadas simultâneas, agilizando o retorno dos dados e passaria as opções na aba de Request Body de forma dinâmica para se adequar a cada possibilidade de consulta.
O resultado será o carregamento do conteúdo da página, e neste ponto, vocÊ usaria o XPath para pegar apenas o miolo que contem a sua resposta.
Uma dica aqui, a página oferece recursos para visualizar o dado como tabela, espaçamento e separador por “;”. A vantagem aqui é que pelo tipo “;”, vocÊ ja teria uma estrutura muito mais enxuta para extrair.
Este seria o resultado da página no navegador:
Você só precisaria achar a parte azulada (div ou tabela em html) para extração já semi pronto. Depois disto, você pode usar o “Cell split node” para quebrar os dados em colunas por conta do separador ser “;”
Desculpe o texto longo, mas este seria o caminho ok? realmente tem que tratar bem os dados, ver todas as opções realmente necessárias para minimizar esforços.
Se forem dados muito específicos, você pode fazer como exemplifiquei acima com o dado fixo para Linha, Coluna , Conteúdo… mudando apenas o período, mas veja que para o período ele codifica/escreve diferente do que se poderia esperar.
Espero ter ajudado
Att,
Denis