使用 beautifulsoup 将 html 表转换为 python 中的 csv

问题描述 投票:0回答:1

我正在尝试从网站获取表格数据。网页上显示了一些产品,我提取了这些产品的链接,并想将这些产品一一转到这些产品,获取表格,并将所有信息合并到一张大表格中。下面的代码仅返回 1 个产品的信息。有人可以帮助我将其扩展到所有产品吗?将是一个很大的帮助,谢谢。

import requests
import xlsxwriter
import csv
from bs4 import BeautifulSoup 
def cpap_spider(max_pages):
    global row_i
    page=1
    while page<=max_pages:
        url= "https://dmesupplyusa.com/bath-aids.html?p=" +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":"product-item-link"}):
            href=link.get("href")
            title = link.string
            #worksheet.write(row_i, 0, title)
            each_item(href)
            print(href)
            #print(title)
        page+=1

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":"data table additional-attributes"})
    rows = table.find_all("tr")

    with open("editors.csv", "wt+", newline="") as f:
        writer = csv.writer(f)
        for row in rows:
            csv_row = []
            for cell in row.findAll(["td", "th"]):
                csv_row.append(cell.get_text())
            writer.writerow(csv_row)
    
cpap_spider(1)
python beautifulsoup html-table
1个回答
0
投票

您必须迭代

cpap_spider
的结果,并且可以创建一个字典列表来存储详细信息页面中的所有相关信息。您可以通过表格中的
pandas.read_html()
或表格中的
beautifulsoup
以及所有其他附加和可用元素获取这些内容。

最后将您的字典列表转换为数据框/csv 或直接转换为 csv。

示例
import requests
import pandas as pd
from bs4 import BeautifulSoup 

def cpap_spider(max_pages):
    url_list = []
    page=1
    while True:
        url= 'https://dmesupplyusa.com/bath-aids.html?p='+str(page)
        soup= BeautifulSoup(requests.get(url).text, 'html.parser')
        for link in soup.select('a.product-item-link[href]'):
            url_list.append({
                'url':link.get('href')
            })

        if page < max_pages:
            page+=1
        else:
            break

    return url_list

def each_item(item_url):
    soup= BeautifulSoup(requests.get(item_url).text, 'html.parser')

    return dict(row.stripped_strings for row in soup.select('table#product-attribute-specs-table tr'))

data = []
for item in cpap_spider(2):
    item.update(each_item(item.get('url')))
    data.append(item)

df = pd.DataFrame(data)
df.to_csv('your_final_file.csv', index=False)
© www.soinside.com 2019 - 2024. All rights reserved.