python - 抓取后删除部分写入 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()
解决方案
您可以在保存之前简单地替换值
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 ", "")
推荐阅读
- amazon-web-services - 将 Google Cloud 与 AWS 连接起来的策略是什么?
- dart - 以下Flutter读/写文件文档是否有浪费的实现?
- ios - 在 Firebase 数据库中使用 WebView
- mysql - rake db:migrate - rake aborted LoadError: dlopen && 安装 mysql2 时出错
- javascript - 在通过 REST 添加基于内容类型的空白项目时,Sharepoint 错误“要将项目添加到文档库,请使用 SPFileCollection.Add()”
- python - 让 nan 陷入困境,并转换均值
- tensorflow - 张量流操作和张量之间的区别?
- python - 从 LSTM caffe 预训练模型中获取 c_0 和 h_0
- macos - 如何在mac os中卸载activemq
- python - 计算一维数组之间的协方差,以纳入 Python 中的不确定性传播