【问题标题】:Pandas for Excel and selenium loop用于 Excel 和硒循环的 Pandas
【发布时间】:2020-11-27 13:06:37
【问题描述】:

我正在尝试从 excel 中打印值,并且值是数字。我的目标是阅读这些值并在谷歌中一一搜索。当值为 'nan' 时将停止 x 秒,然后跳过此 'nan' 并继续前进到下一个。

面临的问题:

  1. 它正在以科学计数法格式打印出来
  2. 想要在 excel 中出现“nan”时停止做某事
  3. 将 UPC[i] 复制到谷歌搜索中,但我只想复制一次,因为我想设计它打开新标签然后复制第二个 UPC[i]

我的解决方案:

  1. 我在 set_option 中有 'lambda x: '%0.2f' % x' 以使其打印出 xxxxxx.00 并带有 2 个小数。即使我想要 int 格式,但它已经比科学记数法格式更好
  2. 使用 'if' 查看 upc[i] 中的值是否等于 'nan'
  3. 我现在想不起来

代码:

import pandas as pd
import numpy as np
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
import msvcrt
import datetime
import time

driver = webdriver.Chrome()
#Settings
pd.set_option('display.width',10, 'display.max_rows', 10, 'display.max_colwidth',100, 'display.width',10, 'display.float_format', lambda x: '%0.2f' % x)

df = pd.read_excel(r"BARCODE.xlsx", skiprows = 2, sheet_name = 'products id')

#Unnamed: 1 is also an empty column, i just didn't input UPC as title in excel.
upc = df['Unnamed: 1']

#I can't print out as interger...It will always have a xxxxx.0
print((upc[0:20]))

count = len(upc)
i = 0
for i in range(count ):
    if upc[i] == 'nan':
        'skip for x seconds and continue, i am not sure how to do yet'
    else:
        print(int(upc[i]))
        driver.get('https://www.google.com')
        driver.find_element_by_name('q').send_keys(int(upc[i]))
        i = i + 1

打印出来:

3337872411991.0
3433422408159.0
3337875598071.0
3337872412516.0
3337875518451.0
3337875613491.0
3337872413025.0
3337875398961.0
3337872410208.0
nan          <- i want program to stop here so i can do something else.
3337872411991.0
3433422408159.0
3337875598071.0
3337872412516.0
3337875518451.0
3337875613491.0
3337872413025.0
3337875398961.0
3337872410208.0
nan
Name: Unnamed: 1, Length: 20, dtype: float64
3337872411991
3433422408159
3337875598071
3337872412516
3337875518451
etc....

在 Google 上搜索了一些关于数字的格式,例如设置打印格式,但我对 .format 和 lambda 感到困惑。

【问题讨论】:

    标签: python-3.x excel pandas selenium


    【解决方案1】:

    它正在以科学计数法格式打印出来

    您似乎有 UPC 和 EAN 之类的数字。 您可以通过将数字标记为文本来解决这个问题。如果您需要始终长度为 13,您可以通过在开始时附加零来纠正它。

    nan 在 excel 中时想要停止做某事

    最简单的解决方案可能是使用输入并接受任何字符来继续执行您的代码。但是如果你想有几秒钟的时间time.sleep() 也不错

    将 UPC[i] 复制到谷歌搜索中,但我只想复制一次,因为我想设计它打开新标签然后复制第二个 UPC[i]

    您可能需要重新考虑的几点:

    • 如果您需要索引值,可以使用enumerate() 在 python 中进行迭代。如果您不需要索引,您可以简单地删除它。 for value in data_frame['UPC']:
    • 使用 selenium,您可以直接抓取结果,而不是使用新标签。

    您可以在下面查看工作示例(至少在我的机器上使用python3w10chrome exe driver)。

    import pandas as pd
    from time import sleep
    from selenium import webdriver
    from selenium.webdriver import ActionChains
    from selenium.webdriver.common.keys import Keys
    
    # Settings
    pd.set_option('display.width', 10, 'display.max_rows', 10, 'display.max_colwidth', 100, 'display.width', 10,
                  'display.float_format', lambda x: '%0.2f' % x)
    
    data_frame = pd.read_excel('test.xlsx', sheet_name='products id', skip_blank_lines=False)
    
    # I have chrome driver in exe, so this is how I need to inject it to get driver out
    driver = webdriver.Chrome('chromedriver.exe')
    google = 'https://www.google.com'
    
    for index, value in enumerate(data_frame['UPC']):  # named the column in excel file
        if pd.isna(value):
            print('{}: zzz'.format(index))
            sleep(2)  # will sleep for 2 seconds, use input() if you want to wait indefinitely instead
        else:
            print('{}: {} {}'.format(index, value, type(value)))
            # since given values are float, you can convert it to int
            value = int(value)
            driver.get(google)
            google_search = driver.find_element_by_name('q')
            google_search.send_keys(value)
            google_search.send_keys('\uE007')  # this is "ENTER" for committing your search in google or Keys.ENTER
    
            sleep(0.5)
            # you may want to wait a bit before page loads fully, then scrape info you want
            # also consider using try-except blocks if something unexpected happens
    
            # if you want to open new tab (windows + chrome driver)
            # open a link in a new window - workaround
            helping_link = driver.find_element_by_link_text('Help')
            actions = ActionChains(driver)
            actions.key_down(Keys.CONTROL).click(helping_link).key_up(Keys.CONTROL).perform()
            driver.switch_to.window(driver.window_handles[-1])
    
    # close your instance of chrome driver or leave it if you need your tabs
    # driver.close()
    

    【讨论】:

      【解决方案2】:
      1. 检查this post
      if upc[i].isnull():
          time.sleep(3)
      
      1. 查看this post,归结为:

        driver.execute_script("window.open('https://www.google.com');") driver.switch_to.window(driver.window_handles[-1])

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-02-13
        • 1970-01-01
        • 2015-10-10
        • 2017-11-21
        • 1970-01-01
        • 2017-08-01
        • 2020-02-14
        相关资源
        最近更新 更多