【发布时间】:2019-12-20 08:40:27
【问题描述】:
更新/解决方案
我决定稍微修改一下代码。我最终使用 pandas read_csv 来打开 urls.csv 并使用 iterrows() 遍历 df 列。现在一切正常。下面是更新后的代码sn-p。
df = pd.read_csv(urls, header=0, encoding="utf8", index_col=False)
for index, row in df.iterrows():
report_type = row[0]
report_name = row[1]
file_name = row[2]
download_report(report_type, report_name, file_name)
----
我正在使用 Selenium 自动化一些报告下载。我编写了过于重复的原始 python 脚本,所以我决定将其组合成一个函数。此函数导航到系统中的特定位置,通过匹配名称生成报告,下载报告并移动/重命名它。
def download_report(q_type, report_name, file):
driver.get(q_type)
driver.find_element_by_xpath("//select[@name='SavedQueriesDropDownList']/option[text()='%s']" % report_name).click()
driver.implicitly_wait(3)
driver.find_element_by_xpath("//input[@type='submit' and @value='Run Query']").click()
driver.implicitly_wait(3)
driver.find_element_by_id('exportsLinksDiv').click()
driver.implicitly_wait(3)
driver.find_element_by_id('ListToolbarRAWEXCELExportLink').click()
time.sleep(5)
filename = max([path + "\\" + f for f in os.listdir(path)], key=os.path.getctime)
print(filename)
os.rename(filename, out_path + file)
我将函数所需的所有数据保存在一个包含三列的 csv 文件中:q_type 是起始 URL 路径,report_name 告诉驱动程序选择哪个报告,file 是我想要的文件名下载的文件要重命名为。
我通过以下方式将所需的值传递给函数:
with open(urls, encoding="utf8") as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='|')
for row in reader:
report_type = row[0]
report_name = row[1]
file_name = row[2]
download_report(report_type, report_name, file_name)
当我运行脚本时,函数 driver.get(q_type) 的第一行出现错误:
Traceback (most recent call last):
File "C:/nf4.py", line 52, in <module>
download_report(report_type, report_name, file_name)
File "C:/nf4.py", line 10, in download_report
driver.get(q_type)
File "C:\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 333, in get
self.execute(Command.GET, {'url': url})
File "C:\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidArgumentException: Message: invalid argument
(Session info: chrome=76.0.3809.100)
为了测试,我从函数中打印出 q_type 的值,并且可以确认它从 csv 文件中提取 url 并将其作为字符串提取。真的不确定错误来自哪里。
我正在使用以下驱动程序设置:
# Setup Chrome Driver
chrome_path = r'C:\drivers\chromedriver.exe'
chrome_options = webdriver.ChromeOptions()
prefs = {'download.default_directory' : r'C:\data-in\raw'}
chrome_options.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(chrome_path, options=chrome_options)
【问题讨论】:
-
不懂 Python,但这看起来不对:...'%s']" % report_name
-
只是为了排除一种可能性,您可以删除 options=chrome_options 参数以查看是否有任何不同吗?
-
@jmq 不一样。
-
尝试从
print(q_type)硬编码driver.get("hardcoded URL")中的url。如果您能够使用引发此错误的 URL 更新问题,那将有所帮助。此外,您只需设置一次driver.implicitly_wait(3),它是隐式,因此一旦设置,它将等待所有find_element调用。它不充当time.sleep()。 -
如果您可以将您的整个
stacktrace放入同样有帮助的问题中,我想看看您使用的是哪种 chrome 和 chromedriver 组合。
标签: python python-3.x selenium webdriver