Created
January 28, 2025 12:43
-
-
Save luxu/93398da15d2abadefcd6f71a1943242c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
from playwright.async_api import async_playwright | |
url = 'https://www.in.gov.br/leiturajornal?secao=dou1&data=27-01-2025' | |
async def crawler(): | |
async with async_playwright() as p: | |
browser = await p.chromium.launch(headless=True) | |
# browser = await p.chromium.launch(headless=False) | |
page = await browser.new_page() | |
await page.goto(url) | |
all_items = [] # Lista para armazenar os links de todas as páginas | |
page_num = 0 | |
while True: | |
print(f"Coletando links da página {page_num}...") | |
# Aguarda os elementos na página carregarem | |
await page.wait_for_selector("li.materia-link.resultados-wrapper") | |
# Extrai os links apenas dos elementos <li> com a classe específica | |
items = await page.eval_on_selector_all( | |
"li.materia-link.resultados-wrapper a", | |
""" | |
elements => elements.map(e => { | |
return { | |
text: e.innerText.trim(), | |
link: e.href | |
}; | |
}) | |
""" | |
) | |
all_items.extend(items) # Adiciona os links da página atual à lista | |
# Verifica se o botão "Próximo" existe | |
next_button = await page.query_selector("span.pagination-button:text('Próximo »')") | |
if next_button and "disabled" not in await next_button.get_attribute( | |
"class"): # Verifica se está habilitado | |
await next_button.click() # Simula o clique no botão "Próximo" | |
await page.wait_for_load_state("networkidle") # Aguarda o carregamento da próxima página | |
page_num += 1 # Incrementa o contador de páginas | |
else: | |
print("Paginação concluída. Não há mais páginas disponíveis.") | |
break # Sai do loop se não houver mais páginas | |
for item in all_items: | |
print(item['text'], item['link']) | |
print(f"Total de links encontrados: {len(all_items)}") | |
await browser.close() | |
if __name__ == "__main__": | |
asyncio.run(crawler()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment