Python,Selenium:从返回列表中隔离项目

时间:2019-07-08 18:30:42

标签: python python-3.x list selenium dictionary

通过阅读,视频,SO以及社区的帮助,我能够使用Selenium和Python从Tessco.com抓取数据。

此网站需要联合国和密码。我已经在下面的代码中包含了此信息,这是非必需的凭据,专门用于询问问题。

我的最终目标是循环浏览零件编号的Excel列表,并搜索包括价格在内的一组参数。在介绍要遍历的列表之前,我希望将所需的信息与废弃的信息隔离开来。

我不确定如何过滤此信息。

代码如下:

    import time
    #Need Selenium for interacting with web elements
    from selenium import webdriver
    from selenium.webdriver.support import expected_conditions as EC
    #Need numpy/pandas to interact with large datasets
    import numpy as np
    import pandas as pd

    chrome_path = r"C:\Users\James\Documents\Python Scripts\jupyterNoteBooks\ScrapingData\chromedriver_win32\chromedriver.exe"
    driver = webdriver.Chrome(chrome_path)
    driver.get("https://www.tessco.com/login")

    userName = "FirstName.SurName321123@gmail.com"
    password = "PasswordForThis123"

    #Set a wait, for elements to load into the DOM
    wait10 = WebDriverWait(driver, 10)
    wait20 = WebDriverWait(driver, 20)
    wait30 = WebDriverWait(driver, 30)

    elem = wait10.until(EC.element_to_be_clickable((By.ID, "userID"))) 
    elem.send_keys(userName)

    elem = wait10.until(EC.element_to_be_clickable((By.ID, "password"))) 
    elem.send_keys(password)

    #Press the login button
    driver.find_element_by_xpath("/html/body/account-login/div/div[1]/form/div[6]/div/button").click()

    #Expand the search bar
    searchIcon = wait10.until(EC.element_to_be_clickable((By.XPATH, "/html/body/header/div[2]/div/div/ul/li[2]/i"))) 
    searchIcon.click()

    searchBar = wait10.until(EC.element_to_be_clickable((By.XPATH, '/html/body/header/div[3]/input'))) 
    searchBar.click()

    #load in manufacture part number from a collection of components, via an Excel file

    #Enter information into the search bar
    searchBar.send_keys("HL4RPV-50" + '\n')

    # wait for the products information to be loaded
    products = wait30.until(EC.presence_of_all_elements_located((By.XPATH,"//div[@class='CoveoResult']")))
    # create a dictionary to store product and price
    productInfo = {}
    # iterate through all products in the search result and add details to dictionary
    for product in products:
        # get product info such as OEM, Description and Part Number
        productDescr = product.find_element_by_xpath(".//a[@class='productName CoveoResultLink hidden-xs']").text
        mfgPart = product.find_element_by_xpath(".//ul[@class='unlisted info']").text.split('\n')[3]
        mfgName = product.find_element_by_tag_name("img").get_attribute("alt")

        # get price
        price = product.find_element_by_xpath(".//div[@class='price']").text.split('\n')[1]

        # add details to dictionary
        productInfo[mfgPart, mfgName, productDescr] = price

    # print products information   
    print(productInfo)

输出为

{('MFG PART #: HL4RPV-50', 'CommScope', '1/2" Plenum Air Cable, Off White'): '$1.89', ('MFG PART #: HL4RPV-50B', 'CommScope', '1/2" Plenum Air Cable, Blue'): '$1.89', ('MFG PART #: L4HM-D', 'CommScope', '4.3-10 Male for 1/2" AL4RPV-50,LDF4-50A,HL4RPV-50'): '$19.94', ('MFG PART #: L4HR-D', 'CommScope', '4.3-10M RA for 1/2" AL4RPV-50, LDF4-50A, HL4RPV-50'): '$39.26', ('MFG PART #: UPL-4MT-12', 'JMA Wireless', '4.3-10 Male Connector for 1/2” Plenum Cables'): '$32.99', ('MFG PART #: UPL-4F-12', 'JMA Wireless', '4.3-10 Female Connector for 1/2" Plenum'): '$33.33', ('MFG PART #: UPL-4RT-12', 'JMA Wireless', '4.3-10 R/A Male Connector for 1/2" Plenum'): '$42.82', ('MFG PART #: L4HF-D', 'CommScope', '4.3-10 Female for 1/2 in AL4RPV-50, LDF4-50A'): '$20.30'}

我只想要自动搜索中引用的内容,因此在此示例中,我将寻找

('MFG PART #: HL4RPV-50', 'CommScope', '1/2" Plenum Air Cable, Off White'): '$1.89'

最终,我打算用项目列表替换HL4RPV-50标签,但是现在,我相信我应该过滤所需的内容。

我怀疑逻辑是否正确,但是我尝试打印任何符合该搜索要求的零件的产品信息,如下所示。

for item in mfgPart:
    if mfgPart == "HL4RPV-50":
        print(productInfo)

但是上面的代码只是像以前一样打印了所有输出。

然后我尝试导入itertools并运行以下命令:

print(dict(itertools.islice(productInfo.items(), 1)))

实际上返回了我想要的订单项,但是不能保证第一个返回的项目就是我要寻找的项目。最好是我可以根据给定的零件号过滤掉确切的搜索内容。

有没有一种方法可以根据输入内容过滤结果?

任何提示都将不胜感激。

3 个答案:

答案 0 :(得分:1)

您的原始示例非常接近,我们只需遍历并检查每个项目,并在字典关键部分中找到列表。如果您不介意嵌套,那么就可以解决问题:)您只需要适当地调整关键字即可。

注意:

如果使用Python 2.X,则可能必须使用productinfo.iteritems(),在这种情况下假设为3.X。

示例:

def main():

""" Get our key from our dictionary """
for key in productinfo.items():

    """ Retrieve our list of strings """
    for stringList in key[0]:

        """ For every new line in our list of strings """
        for newline in stringList.splitlines():

            """ Lets split by each word in our line """
            for string in newline.split(' '):

                """ Check each string against our keyword """
                if string == "HL4RPV-50B":
                    print(key)

if __name__ == '__main__':
    main()

答案 1 :(得分:1)

其他答案似乎在检查零件号是否在mfg零件字符串中,但是我看到某些项目可能包含相同的零件号,例如HL4RPV-50HL4RPV-50B。如果要隔离部件号,以便您可以准确地知道要查找的部件,我建议遍历字典,并在冒号处分割mfg部件字符串以获取ID。您还可以抓取项目的其他部分,以更清晰地打印出信息,如下例所示。

for (mfg_part, comm_scope, name), price in productInfo.items():
    mfg_id = mfg_part.split(': ')[1]
    if mfg_id == 'HL4RPV-50':
        print('Part #:', mfg_id)
        print('Company:', comm_scope)
        print('Name:', name)
        print('Price:', price)

答案 2 :(得分:0)

您可以将此过滤器代码用于Python字典

 searchedProduct = dict(filter(lambda item: "HL4RPV-50" in item[0], productInfo.items()))
 print(searchedProduct)