首页 > 解决方案 > 在列表元素中获取子字符串 Python - Web Scraping

问题描述

请原谅我是 Python 和 Selenium 的新手。我正在抓取一个超市网站。我得到的项目名称如下,其中有名称的数量。我想为不同的案例和项目从名称中提取数量,如下所示 -

案例

新鲜价值芋头 250g

新鲜价值香蕉罗布斯塔 1kg

Fresh Value 生木瓜 1 U (units) (300g-400g)

Fresh Value 优质石榴喀布尔 (500g - 700g)

需要的输出:

名称 = Fresh Value Colocasia, 数量 = 250g

名称 = Fresh Value Banana Robusta,数量 = 1kg

名称 - 新鲜价值生木瓜,数量 = 1 U(单位)(300g-400g)

它有数百个这样的项目。我试过使用

str.split()

但没有得到输出。我也尝试过使用正则表达式,但不确定它是如何工作的。有没有一种方法可以在我在字符串中找到一个数字后拆分字符串?任何建议可能会有所帮助。

标签: pythonpython-3.xseleniumweb-scrapingweb-crawler

解决方案


One option (according to the data samples that you provided) can be this:

import re
strings = ['Fresh Value Colocasia 250g', 'Fresh Value Banana Robusta 1kg', 'Fresh Value Raw Papaya 1 U (units) (300g-400g)','Fresh Value Premium Pomegranate Kabul (500g - 700g)']
for i in strings:
    start = re.findall('\d|\(', i)[0]
    name = i.split(start)[0].strip()
    quantity = start + i.split(start)[1]
    print 'Name = '+ name + ', Quantity = ', quantity

Output:

Name = Fresh Value Colocasia, Quantity =  250g
Name = Fresh Value Banana Robusta, Quantity =  1kg
Name = Fresh Value Raw Papaya, Quantity =  1 U (units) (300g-400g)
Name = Fresh Value Premium Pomegranate Kabul, Quantity =  (500g - 700g)

Of course it is valid if the numbers and parenthesis are present only in the quantity and not in the name. If the quantity starts with other symbols, you can add them in findall


推荐阅读