简体   繁体   English

如何在列中打印事物列表?

[英]How to print a list of things in columns?

Currently I am working on some selenium code and I wrote a code to simply go to some website, search for a few products and then list them. 目前,我正在编写一些selenium代码,并编写了一个代码来简单地访问某些网站,搜索一些产品,然后列出它们。 Everything works good except one thing. 除了一件事外,一切都运作良好。 I want to print the products in this format: 我要以这种格式打印产品:

 1. <name>\t<price>
 2. <name>\t<price> ...

The problem is that some of the products (in my particular case one of them) names are longer than the other, which produces output like this: 问题在于某些产品(在我的特定情况下,其中一种)的名称比另一种的名称长,这会产生如下输出:

1. Nóż Benchmade 62 Balisong    1 275,00 zł
2. Nóż Benchmade 63 Balisong Bowie      1 290,00 zł
3. Nóż Benchmade 67 Balisong    1 295,00 zł
4. Nóż Benchmade 87 Ti Balisong 2 235,00 zł

As you can see, if I just add one or two \\t s, it would be okay, but I don't think it's a particularly good way to do this. 如您所见,如果我仅添加一个或两个\\t ,这是可以的,但是我认为这不是一种特别好的方法。

So the question is: How do I align text in column-way without manually calculating the size of the longest record in the column? 所以问题是:如何在不手动计算列中最长记录大小的情况下以列方式对齐文本? (Maybe there is a standard lib-way to do this, or maybe 3rd party lib?) (也许有一个标准的库方式可以做到这一点,或者也许是第三方库?)

Edit: I've added the code: 编辑:我添加了代码:

from selenium import webdriver

class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def __str__(self):
        return f'{self.name}\t{self.price}'

    def __repr__(self):
        return f'Product({self.name})'        

def search_for(driver, input_name, query):
    search_field = driver.find_element_by_name(input_name)
    search_field.clear()
    search_field.send_keys(query)
    search_field.submit()


def create_products(driver):
    found_elements = driver.find_elements_by_xpath("//div[@class='wrapper']")
    names = [
        fe.find_element_by_xpath(".//img[@alt]").get_attribute("alt")
        for fe in found_elements
    ]
    products = []
    int_parts = driver.find_elements_by_xpath(
        "//span[@class='price']/span[@class='price-integer-part']")
    decimal_parts = driver.find_elements_by_xpath(
        "//span[@class='price']/span[@class='price-decimal-part']")
    currencies = driver.find_elements_by_xpath(
        "//span[@class='price-currency']")
    for info in zip(names, int_parts, decimal_parts, currencies):
        name, int_part, decimal_part, currency = info
        price = f'{int_part.text},{decimal_part.text} {currency.text}'
        products.append(Product(name, price))
    return products


def main():
    driver = webdriver.Chrome()
    driver.implicitly_wait(30)
    driver.maximize_window()

    driver.get('https://kolba.pl')
    search_for(driver, 'query', 'benchmade balisong')
    products = create_products(driver)
    print(f'Found {len(products)} products:\n')
    for i, product in enumerate(products):
        print(f'{i+1}. {product}')


if __name__ == '__main__':
    main()

I actually found the answer myself: humanfriendly library. 我实际上找到了答案: humanfriendly图书馆。

Just added this code: 刚刚添加了以下代码:

from humanfriendly.tables import format_pretty_table

Changed my Product class to: 将我的Product类别更改为:

class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def __str__(self):
        return f'{self.name}\t{self.price}'

    def __repr__(self):
        return f'Product({self.name})'

    def __iter__(self):
        return iter((self.name, self.price))

And printed it out: 并打印出来:

column_names = ['Name', 'Price']
print(format_pretty_table(products, column_names))

where products is a list of objects of type Product . 其中productsProduct类型的对象的列表。

Given output: 给定输出:

-------------------------------------------------
| Name                            | Price       |
-------------------------------------------------
| Nóż Benchmade 62 Balisong       | 1 275,00 zł |
| Nóż Benchmade 63 Balisong Bowie | 1 290,00 zł |
| Nóż Benchmade 67 Balisong       | 1 295,00 zł |
| Nóż Benchmade 87 Ti Balisong    | 2 235,00 zł |
-------------------------------------------------

And I didn't have to use fixed-size strings (total waste and it just looks ugly) plus I didn't have to calculate by hand. 而且,我不必使用固定大小的字符串(总浪费,而且看起来很丑陋),而且我也不需要手工计算。 So I guess that would be an answer to my question, so happy to find that library 所以我想这将是我的问题的答案,很高兴找到那个图书馆

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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