无法在 Python 中打印

Can't print in Python

我最近几周一直在研究 Python 以自动化我的业务工作。

基本上我必须进行网络抓取,但我在倒数第二行代码中的打印功能遇到问题...

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()

检查xpath是否确实是你想通过selenium获取的文本的正确路径。

如果这是一个网站,您可以转到您要查找的元素并右键单击并select 复制 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)

首先,我建议概括您的 xpath 查询。目前,它严重依赖于整个页面的结构。页面不相关部分的小布局更改可能会给您带来不良结果。复习 xpath syntax // 和谓词的使用,将来会为您省去很多麻烦。

如果这没有帮助,请 post 您正在尝试解析的 html。