我有一个链接,在这个链接中,我有一些产品。每种产品都有一个规格表。该表的第一列应该是标题,第二列应该是与之对应的数据。每个表的第一列都不同,有一些重叠的类别。我想得到一个大桌子,上面有所有这些类别,每行都有不同的产品。我能够获得一个表(一种产品)的数据,如下所示:
import requests
import csv
from bs4 import BeautifulSoup
def cpap_spider(max_pages):
page=1
while page<=max_pages:
url= "https://www.1800cpap.com/cpap-masks/nasal?page=" +str(page)
source_code= requests.get(url)
plain_text= source_code.text
soup= BeautifulSoup(plain_text, 'html.parser')
for link in soup.findAll("a", {"class":"facets-item-cell-grid-title"}):
href="https://www.1800cpap.com"+link.get("href")
title= link.string
each_item(href)
print(href)
#print(title)
page+=1
data=[]
def each_item(item_url):
source_code= requests.get(item_url)
plain_text= source_code.text
soup= BeautifulSoup(plain_text, 'html.parser')
table=soup.find("table", {"class":"table"})
table_rows= table.find_all('tr')
for row in table_rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
data.append([ele for ele in cols if ele]) # Get rid of empty values
b = open('all_appended.csv', 'w')
a = csv.writer(b)
a.writerows(data)
b.close()
cpap_spider(1)
这段代码将一个接一个地追加所有表。但是,我想要一个在第一行中具有唯一标题的大表,以及按顺序排列的相应产品值
假设标题始终是每个表的第一行,则只需跳过每个表中的该行,但不包括第一行。一种简单的方法是将要处理的第一行存储在初始化为0的变量中,并在处理函数中将其设置为1。可能代码:
使用
xlsxwriter
而不是csv
因为如果文本包含一个逗号,旁边没有空格","
而不是逗号,旁边有空格", "
,那么您的csv文件将出现问题,因为每个列值都由","
分隔。例如,如果text = "aa,bb"
,csv将认为此文本包含两列,如"aa"
和"bb"
。这就是你需要的
相关问题 更多 >
编程相关推荐