简体   繁体   中英

Can't print in Python

I've been studying Python last few weeks to automate a work for my business.

Basically I have to do webscraping but I'm having trouble with a print function in the next-to-last code line...

def search_time(self):
    for item in self.items:
        print(f"Procurando {item}.")

        self.driver.get(self.bot_url)

        cpfBox = self.driver.find_element_by_xpath('//*[@id="search"]/div/div[1]/input')
        cpfBox.send_keys(item)

        time.sleep(2)

        cpfButton = self.driver.find_element_by_xpath('//*[@id="search"]/div/div[2]/button')
        cpfButton.click()

        time.sleep(2)

        self.delay = 3  # seconds



    try:
        WebDriverWait(self.driver, self.delay).until(EC.presence_of_element_located((By.XPATH, '//*[@id="main"]/div[1]/h2')))
        print('CPF Valido')
    except TimeoutException:
        print('CPF Invalido')

        time.sleep(2)

        name = self.driver.find_element_by_xpath("/html/body/main[1]/div[1]/div[1]/div[1]/div[1]/h2").text
        print(name)

        time.sleep(2)


items = ["32911769953"]


bot_url = BOT(items)
bot_url.search_time()

Check whether the xpath is indeed the correct path to the text you want to get through selenium.

If this is a website you can go to the element that you are trying to find and right click and select Copy XPATH.

try:
    WebDriverWait(self.driver, self.delay).until(EC.presence_of_element_located((By.XPATH, '//*[@id="main"]/div[1]/h2')))
    name = self.driver.find_element_by_xpath("/html/body/main[1]/div[1]/div[1]/div[1]/div[1]/h2").text
    print(name)
    time.sleep(2)
    print('CPF Valido')
except TimeoutException:
    print('CPF Invalido')
    time.sleep(2)

First, I would recommend generalizing your xpath query. Currently, it is heavily dependent on the entire page's structure. A small layout change in an unrelated part of the page could give you undesirable results. Review xpath syntax use of // and predicates will save you many headaches in the future.

If that doesn't help, please post the html that you are attempting to parse.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM