0

我已经构建了一个刮板,虽然它似乎在提取正确的 HTML,但当我遍历容器标签时,它似乎只提取了一条记录。我是一个菜鸟,所以我希望我错过了一些简单的东西,但是几个小时的研究让我很难过。

我已经搜索了一个解决方案,并确保它实际上提取了我需要的所有 HTML。然而,当我最后运行这段代码时,我只得到一个结果而不是所有结果。当我导出到 .csv 时也是如此。

print("product_name: " + product_name)
print("product_number: " + product_number)
print("category: " + category)

这是相关的代码:

containers = page_soup.findAll("tr",{"class":"Product"})

for container in containers:

    product_name = container.a.text

    product_number = container.div.text

    category_container = container.select_one('td:nth-of-type(4)').text.strip()
    category = category_container

我希望得到超过 1000 种产品的输出,但我只得到一种。我错过了什么?任何帮助将不胜感激。

4

1 回答 1

1

变量product_name, product_number,category只能保留一个值 - 循环中的最后一个值。

所以你可以使用print()内部循环来查看值

import csv

f = open(filename, 'w')
csv_writer = csv.writer(f)

# header
csv_writer.writerow( ["Product Name", "Product number", "Category"] ) 

for container in containers:
    product_name = container.a.text
    product_number = container.div.text
    category = container.select_one('td:nth-of-type(4)').text.strip()

    # single row 
    csv_writer.writerow( [product_name, product_number, category] ) 

    print("product_name:", product_name)
    print("product_number:", product_number)
    print("category: ", category)

f.close()

或者您必须创建列表并使用append()将值添加到列表

product_name = []
product_number = []
category = []

for container in containers:
    product_name.append( container.a.text )
    product_number.append( container.div.text )
    category.append( container.select_one('td:nth-of-type(4)').text.strip() )

#--- later ---

print("product_name:", product_name)
print("product_number:", product_number)
print("category: ", category)    


f = open(filename, 'w')
csv_writer = csv.writer(f)

# header
csv_writer.writerow( ["Product Name", "Product number", "Category"] ) 

for a, b, c in zip(product_name, product_number, category):
    # single row 
    csv_writer.writerow( [a, b, c] ) 

f.close()

编辑:您也可以将其作为字典列表保存

all_items = []    

for container in containers:
    item = {
        'product_name': container.a.text,
        'product_number': container.div.text,
        'category': container.select_one('td:nth-of-type(4)').text.strip(),
    }
    all_items.append(item)

# --- later ---

f = open(filename, 'w')
csv_writer = csv.writer(f)

# header
csv_writer.writerow( ["Product Name", "Product number", "Category"] ) 

for item in all_items:
    print("product_name:", item['product_name'])
    print("product_number:", item['product_number'])
    print("category: ", item['category'])    

    # single row 
    csv_writer.writerow( [item['product_name'], item['product_number'], item['category']] ) 

f.close()
于 2019-05-04T13:48:11.420 回答