如何使用Selenium跳过“无法在类名中找到元素”错误

时间:2016-09-14 12:41:08

标签: python-3.x selenium-webdriver

以下代码执行我需要它做的事情,除非它遇到缺少class_name的产品,比如说product-price。我需要帮助的是如何跳过该特定项目并转到下一个项目。目前我收到以下错误:

“selenium.common.exceptions.NoSuchElementException:消息:{”errorMessage“:”无法找到具有类名'product-display-price'的元素“,”request“:{”headers“:{”Accept“: “应用程序/ JSON”, “接受编码”: “同一性”, “连接”: “关闭”, “内容长度”: “138”, “内容类型”:“应用/ JSON;字符集= UTF-8 “ ”主机“: ”127.0.0.1:64186","User-Agent":"Python-urllib/3.5"},"httpVersion":"1.1","method":"POST","post“:” {\“id \”:\“:wdc:1473855489054 \”,\“value \”:\“product-display-price \”,\“using \”:\“class name \”,\“sessionId \” :\“48018400-7a75-11e6-b0ab-5f6a864b5c88 \”}“,”url“:”/ element“,”urlParsed“:{”anchor“:”“,”query“:”“,”file“:”元件”, “目录”: “/”, “路径”: “/元件”, “相对的”: “/元件”, “端口”: “”, “宿主”: “”, “密码”: “”, “用户”: “”, “用户信息”: “”, “权威”: “”, “协议”: “”, “源”: “/元件”, “queryKey”:{}, “块”:[”元件 “]}”,urlOriginal “:”/会话/ 48018400-7a75-11e6-b0ab-5f6a864b5c88 /元件/:WDC:1473855489054 /元件 “}}”
import csv
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException

b = open('csv/homedepotfridges.csv', 'w', newline='')
a = csv.writer(b,delimiter=',')

driver = webdriver.PhantomJS()
driver.get('https://www.homedepot.ca/en/home/categories/appliances/dishwashers.html#!p=0&q=*%3Aprice-asc%3AcategoryPathHierarchy%3A2%2Fhd-classes%2Fl1-appliances%2Fl2-dishwashers')
items = []

for item in driver.find_elements_by_class_name('item'):
    try:
        model = item.find_element_by_class_name('product-model')
        price = item.find_element_by_class_name('product-display-price')
        title = item.find_element_by_class_name('product-title')
        url = item.find_element_by_class_name('js-detail-link')

        items.append({'model': model, 'price': price, 'title': title, 'url': url})
        print (model.text, price.text, title.text, url.get_attribute("href"))
        c = (model.text, price.text, title.text, url.get_attribute("href"))
        a.writerow(c)

    except NoSuchElementException:
        model = 'n/a'
        price = 'N/A'
        title = 'N/A'
        url = 'N/A'
        items.append({'model': model, 'price': price, 'title': title, 'url': url})
        print(model.text, price.text, title.text, url.get_attribute("href").text)
        c = (model.text, price.text, title.text, url.get_attribute("href"))
    a.writerow(c)


b.close()
  

追踪(最近一次通话):     文件“/Users/User/PycharmProjects/Test/HomeDepotDishwashers.py”,第31行,       print(model.text,price.text,title.text,url.get_attribute.text(“href”))   AttributeError:'str'对象没有属性'text'

感谢任何帮助

1 个答案:

答案 0 :(得分:0)

有几种方法可以做到这一点。你尝试过吗?

1)尝试围绕该行 - 除了https://docs.python.org/3/tutorial/errors.html

  //
// -------------------- clsFullSentences -----------------------------
//
vector<FullSentence> &clsFullSentences::Content()
{
    return m_content;
}
vector<wstring> &clsFullSentences::CleanLower()
{
    return m_sCleanLower;
}
void clsFullSentences::LoadSerializedFullSentences(string uFile)
{
    if (!fileExists(stringToWString(uFile)))
    {
        DebugBreak();
    }

    FILE* inFile =  fopen(uFile.c_str(), "rb");

    wchar_t signature[2];
    fread(signature, sizeof(wchar_t), 1, inFile);

    wstring wline;

    //read how many possibleresults we have     
    getLineW(inFile, wline);

    unsigned int count=_wtoi(wline.c_str());

    for (unsigned int i = 0; i < count; i++)
    {
        FullSentence st;

        getLineW(inFile,wline);
        st.Text = wline;

        //getLineW(inFile,wline);
        st.Emotion =0;// _wtoi(wline.c_str());

        getLineW(inFile,wline);
        st.ByteStart = _wtoi(wline.c_str());

        getLineW(inFile,wline);
        st.ByteCount = _wtoi(wline.c_str());

        m_content.push_back(st);
    }

    fclose(inFile);
}
void clsFullSentences::Add(wstring text, int i1, int i2, int i3)
{
    FullSentence fs;
    fs.Text = text;
    fs.Emotion = i1;
    fs.ByteStart = i2;
    fs.ByteCount = i3;
    m_content.push_back(fs);

    wstring sClean;
    sClean=StripPuncToLower(text);

    m_sCleanLower.push_back(sClean);
}

bool getLineW(FILE *inFile, wstring &result)
{
    wchar_t data[2] = { 0, 0 };

    result = L"";
    do
    {
        fread(data, sizeof(wchar_t), 1, inFile);

        if (data[0] > 0)
        {
            if (data[0] != 13)
            {
                if (data[0] != 10)
                {
                    result += data;
                }
                else
                {
                    break;//10 is the end of the line
                }
            }
        }
    } while (!feof(inFile));

    if (result.size() > 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

2)使用if语句检查是否找到此项。你可以通过列出所有这些元素(find_elements_by _...)来查看该列表的长度是否大于0.例如: