我试图用Python编写一个脚本,从下面的URL中将Product Attributes表导出为Excel文件(或CSV).

我编写了一个脚本并try 了一个不同的类名,但我遇到了一个错误!

URL: https://www.digikey.com/en/products/detail/texas-instruments/uln2003aidre4/1912622

我不知道这条消息是什么原因,因为我可以从不同的网站导出表,但我的代码在这个网站上崩溃了.(还有Mouser.com)

我有一个理论,我认为这两个网站屏蔽了我的脚本,以避免输出他们的数据,但我不确定.

The table I want to export and its inspection table to export

以下是我的代码:

import time
import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import pandas as pd

def get_specifications_table(url):
    options = Options()
    options.add_argument('--headless')  # Run the browser in headless mode (no visible window)

    driver = webdriver.Chrome(options=options)

    driver.get(url)
    time.sleep(5)  # Add a delay to allow the webpage to load (adjust the time as needed)

    try:
        # Find the element with the specified class name "MuiTable-root css-u6unfi" and extract the table
        class_name = "MuiTable-root.css-u6unfi"
        table_element = driver.find_element("css selector", f".{class_name}")
        table_html = table_element.get_attribute('outerHTML')
        df = pd.read_html(table_html)[0]
        return df
    except Exception as e:
        print("Error:", e)
    finally:
        driver.quit()

    return None

def export_to_excel(df, output_file):
    writer = pd.ExcelWriter(output_file, engine='xlsxwriter')
    df.to_excel(writer, index=False)
    writer.save()
    writer.close()

if __name__ == '__main__':
    url = "https://www.digikey.com/en/products/detail/texas-instruments/uln2003aidre4/1912622"
    output_excel_file = "Specifications_Table_Digikey.xlsx"

    print("Fetching the webpage and extracting the table...")
    specifications_df = get_specifications_table(url)
    
    if specifications_df is not None:
        print("Exporting the table to Excel...")
        export_to_excel(specifications_df, output_excel_file)
        print(f"Table 'Specifications' exported to '{output_excel_file}' successfully.")
    else:
        print("Table extraction or export failed.")

但我面对的是这样一个错误:

Fetching the webpage and extracting the table...
Error: Message: no such element: Unable to locate element: {"method":"css selector","selector":".MuiTable-root.css-u6unfi"}
  (Session info: headless chrome=115.0.5790.110); For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception
Stacktrace:
Backtrace:
    GetHandleVerifier [0x004BA813+48355]
    (No symbol) [0x0044C4B1]
    (No symbol) [0x00355358]
    (No symbol) [0x003809A5]
    (No symbol) [0x00380B3B]
    (No symbol) [0x003AE232]
    (No symbol) [0x0039A784]
    (No symbol) [0x003AC922]
    (No symbol) [0x0039A536]
    (No symbol) [0x003782DC]
    (No symbol) [0x003793DD]
    GetHandleVerifier [0x0071AABD+2539405]
    GetHandleVerifier [0x0075A78F+2800735]
    GetHandleVerifier [0x0075456C+2775612]
    GetHandleVerifier [0x005451E0+616112]
    (No symbol) [0x00455F8C]
    (No symbol) [0x00452328]
    (No symbol) [0x0045240B]
    (No symbol) [0x00444FF7]
    BaseThreadInitThunk [0x772500C9+25]
    RtlGetAppContainerNamedObjectPath [0x77BC7B4E+286]
    RtlGetAppContainerNamedObjectPath [0x77BC7B1E+238]

Table extraction or export failed.

推荐答案

要从网站ULN2003AIDRE4 Texas Instruments | Integrated Circuits (ICs) | DigiKey107表中获取数据,您需要推导出visibility_of_element_located()WebDriverWait<table>元素的visibility_of_element_located(),并使用PandasDataFrame,您可以使用以下locator strategy:

代码块:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import pandas as pd

options = Options()
options.add_argument('--headless=new')
options.add_argument("start-maximized")
driver = webdriver.Chrome(options=options)
driver.get("https://www.digikey.com/en/products/detail/texas-instruments/uln2003aidre4/1912622")
time.sleep(10)
table_data = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div[data-evg='product-details-product-attributes'] table.MuiTable-root"))).get_attribute("outerHTML")
df = pd.read_html(table_data)
print(df)
driver.quit()

输出控制台:

[                          Type                                        Description  Select
0                     Category  Integrated Circuits (ICs)Power Management (PMI...     NaN
1                          Mfr                                  Texas Instruments     NaN
2                       Series                                           ULx200xA     NaN
3                      Package                                   Tape & Reel (TR)     NaN
4               Product Status                           Discontinued at Digi-Key     NaN
5                  Switch Type                             Relay, Solenoid Driver     NaN
6            Number of Outputs                                                  7     NaN
7         Ratio - Input:Output                                                1:1     NaN
8         Output Configuration                                           Low Side     NaN
9                  Output Type                                         Darlington     NaN
10                   Interface                                           Parallel     NaN
11              Voltage - Load                                          50V (Max)     NaN
12  Voltage - Supply (Vcc/Vdd)                                       Not Required     NaN
13      Current - Output (Max)                                              500mA     NaN
14                Rds On (Typ)                                                  -     NaN
15                  Input Type                                          Inverting     NaN
16                    Features                                                  -     NaN
17            Fault Protection                                                  -     NaN
18       Operating Temperature                                 -40°C ~ 105°C (TA)     NaN
19               Mounting Type                                      Surface Mount     NaN
20     Supplier Device Package                                            16-SOIC     NaN
21              Package / Case                     16-SOIC (0.154", 3.90mm Width)     NaN
22         Base Product Number                                            ULN2003     NaN]

参考文献

您可以在中找到几个相关的详细讨论:

Python相关问答推荐

在Windows上启动新Python项目的正确步骤顺序

使用pandas、matplotlib和Yearbox绘制时显示错误的年份

我必须将Sigmoid函数与r2值的两种类型的数据集(每种6个数据集)进行匹配,然后绘制匹配函数的求导.我会犯错

连接两个具有不同标题的收件箱

如何在箱形图中添加绘制线的传奇?

'discord.ext. commanders.cog没有属性监听器'

修复mypy错误-赋值中的类型不兼容(表达式具有类型xxx,变量具有类型yyy)

Pandas Loc Select 到NaN和值列表

使用Python从URL下载Excel文件

如何在Python中使用Pandas将R s Tukey s HSD表转换为相关矩阵''

Python—压缩叶 map html作为邮箱附件并通过sendgrid发送

在matplotlib中使用不同大小的标记顶部添加批注

如何获取Python synsets列表的第一个内容?

python sklearn ValueError:使用序列设置数组元素

Python—为什么我的代码返回一个TypeError

判断Python操作:如何从字面上得到所有decorator ?

如何根据rame中的列值分别分组值

Autocad使用pyautocad/comtypes将对象从一个图形复制到另一个图形

如何获取包含`try`外部堆栈的`__traceback__`属性的异常

如何在SQLAlchemy + Alembic中定义一个"Index()",在基表中的列上