【发布时间】:2020-10-16 18:21:45
【问题描述】:
我有一个链接,在该链接中,我有一些产品。在这些产品中的每一个中,都有一个规格表。该表是这样的,第一列应该是标题,第二列是与之对应的数据。这些表中的每一个的第一列都不同,有一些重叠的类别。我想得到一张包含所有这些类别的大表,并且成行显示不同的产品。我能够获取一张表(一种产品)的数据,如下所示:
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)
此代码一个接一个地获取所有附加的表。但是,我想要一个大表,第一行有唯一的标题,并按顺序排列相应的产品值。
【问题讨论】:
标签: python