首页 > 解决方案 > 在python中使用beautifulsoup提取表数据时出现问题

问题描述

下面的代码以表格的形式为我提供了所需的产品数据。它适用于大多数链接,但在某些链接中会停止,给出错误NoneType对象find_alltable.find_all('tr).

我相信这是因为某些产品中不存在表,所以我尝试在表的存在上创建一个 if 条件,但这似乎也无济于事。我应该在下面的代码中进行哪些更改?

import requests, json, time
from bs4 import BeautifulSoup
import pandas as pd

url = "https://www.1800wheelchair.com/category/toilet-accessories/?p="
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0'}

data = []

for i in range(1,3):
    print(i)
    res = requests.get(url + str(i), headers=headers)
    soup = BeautifulSoup(res.text, "html.parser")
    p_links = [i["data-link"] for i in soup.find("ul", {"id":"products-list"}).find_all("li",class_=["openlink","item"])]

    for prod_url in p_links:
        print(prod_url)
        temp = {"Product URL": prod_url}
        prod_res = requests.get(prod_url, headers = headers)
        prod_soup = BeautifulSoup(prod_res.text, "html.parser")

        for p in prod_soup.find("div", class_="basic-information").find_all("p"):
            if "item" in p.text.lower(): temp["item number"] = p.find("span").text.strip()
            elif "brand" in p.text.lower(): temp["manufacturer"] = p.find("span").text.strip()
            elif "sku" in p.text.lower(): temp["sku"] = p.find("span").text.strip()
    
        table = prod_soup.find("table",{"class":"specifications"})
        for tr in table.find_all("tr"):
            temp[tr.find("td", {"class":"tdLabel"}).text.strip()] = tr.find("td", {"class":"tdValue"}).text.strip()
        data.append(temp)
        

pd.DataFrame(data).to_csv("toilet-acc.csv", index=False)

标签: pythonbeautifulsoup

解决方案


您可以使用TryExcept文档)

try:
    for tr in table.find_all("tr"):
        temp[tr.find("td", {"class":"tdLabel"}).text.strip()] = tr.find("td", {"class":"tdValue"}).text.strip()
except:
    pass

推荐阅读