Answer a question

I'm trying to get a value that is given by the website after a click on a button.

Here is the website: https://www.4devs.com.br/gerador_de_cpf

You can see that there is a button called "Gerar CPF", this button provides a number that appears after the click.

My current script opens the browser and get the value, but I'm getting the value from the page before the click, so the value is empty. I would like to know if it is possible to get the value after the click on the button.

from selenium import webdriver
from bs4 import BeautifulSoup
from requests import get

url = "https://www.4devs.com.br/gerador_de_cpf"

def open_browser():
    driver = webdriver.Chrome("/home/felipe/Downloads/chromedriver")
    driver.get(url)
    driver.find_element_by_id('bt_gerar_cpf').click()

def get_cpf():
    response = get(url)

    page_with_cpf = BeautifulSoup(response.text, 'html.parser')

    cpf = page_with_cpf.find("div", {"id": "texto_cpf"}).text

    print("The value is: " + cpf)


open_browser()
get_cpf()

Answers

open_browser and get_cpf are absolutely not related to each other...

Actually you don't need get_cpf at all. Just wait for text after clicking the button:

from selenium.webdriver.support.ui import WebDriverWait as wait

def open_browser():
    driver = webdriver.Chrome("/home/felipe/Downloads/chromedriver")
    driver.get(url)
    driver.find_element_by_id('bt_gerar_cpf').click()
    text_field = driver.find_element_by_id('texto_cpf')
    text = wait(driver, 10).until(lambda driver: not text_field.text == 'Gerando...' and text_field.text)
    return text

print(open_browser())

Update

The same with requests:

import requests

url = 'https://www.4devs.com.br/ferramentas_online.php'
data = {'acao': 'gerar_cpf', 'pontuacao': 'S'}
response = requests.post(url, data=data)
print(response.text)
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐