目前我正在处理一些selenium
代码,我编写了一个代码,只需访问某个网站,搜索一些产品然后列出它们。除了一件事,一切都很好。我想以这种格式打印产品:
1. <name>\t<price>
2. <name>\t<price> ...
问题是某些产品(在我的特殊情况下是其中一个)的名称比另一个更长,产生如下输出:
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ł
正如您所看到的,如果我只添加一个或两个\t
,那就没关系,但我认为这不是一个特别好的方法。
所以问题是:如何在不手动计算列中最长记录的大小的情况下以列方式对齐文本? (也许有一种标准的lib方式可以做到这一点,或者可能是第三方lib?)
编辑:我已添加代码:
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()
答案 0 :(得分:1)
我实际上自己找到了答案:humanfriendly
库。
刚添加此代码:
from humanfriendly.tables import format_pretty_table
将我的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))
打印出来:
column_names = ['Name', 'Price']
print(format_pretty_table(products, column_names))
其中products
是Product
类型的对象列表。
给定输出:
-------------------------------------------------
| 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ł |
-------------------------------------------------
而且我不必使用固定大小的字符串(总浪费而且看起来很难看)加上我没有必须手工计算。所以我想这将是我的问题的答案,很高兴找到该库