首页 > 解决方案 > 抓取后删除部分写入 CSV 的文本

问题描述

我正在使用一个脚本来解析这个网站的组件库存号、价格、HSN 代码等。我正在从库存号列表(如下所示)构建 URL,然后BeautifulSoup用于抓取网站的部分内容。我能够看到我需要的输出(如下所示)并将其写入 CSV 文件。

在此处输入图像描述

如何摆脱 text RS Stock No.HSN Code并且Brand只将值写入 CSV?内容rs_tmp.csv如下:

553431
553437
553453
6738708

代码如下,

from bs4 import BeautifulSoup
import requests
import csv

with open('csv/rs_tmp.csv', 'w', newline='') as csvfile:
    rs_cmp_writer = csv.writer(csvfile)

    with open('urls_folder/rs_tmp.txt', 'r') as url_file:
        for line in url_file:
            url = "https://in.rsdelivers.com/productlist/search?query=" + line.lstrip()
            cmp_data = []

            source = requests.get(url).text
            soup = BeautifulSoup(source, 'lxml')

            for snippet in soup.find_all('div', class_='row-inline pill-component-module_pill-component__1WRtv pill-component-module_grey__38ctb'):
                stock_num_part_num = snippet.text
                cmp_data.append(stock_num_part_num)

            for snippet in soup.find_all('div', class_='add-to-basket-cta-component_price-block__1agRR'):
                price = snippet.div.p.text
                cmp_data.append(price)

            rs_cmp_writer.writerow(cmp_data)

print()

标签: pythoncsvbeautifulsoup

解决方案


您可以在保存之前简单地替换值

if len(cmp_data) > 2:
    cmp_data[0] = cmp_data[0].replace("RS Stock No. ", "") 
    cmp_data[1] = cmp_data[1].replace("Brand ", "")
    cmp_data[2] = cmp_data[2].replace("HSN Code ", "")

rs_cmp_writer.writerow(cmp_data)

编辑:

最终你可以在一行中完成,但这将不那么可读。

stock_num_part_num = snippet.text.replace("RS Stock No. ", "").replace("HSN Code ", "").replace("Brand ", "")

推荐阅读