【发布时间】:2023-03-12 07:43:01
【问题描述】:
我目前正在尝试编写一个脚本,从网站上获取一些价格,然后我想将它集成到一个 csv 文件中。现在用一个项目运行它时,它工作正常。但是,当我尝试再次打开浏览器时,出现以下错误:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Program Files\JetBrains2\PyCharm Community Edition 2020.2.3\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
File "C:\Program Files\JetBrains2\PyCharm Community Edition 2020.2.3\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/timjo/Desktop/BOTSCRIPT/Test.py", line 13, in <module>
driver.get('https://buff.163.com/market/goods?goods_id=40086&from=market#tab=selling')
File "C:\Users\timjo\Desktop\BOTSCRIPT\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 333, in get
self.execute(Command.GET, {'url': url})
File "C:\Users\timjo\Desktop\BOTSCRIPT\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\timjo\Desktop\BOTSCRIPT\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidSessionIdException: Message: Tried to run command without establishing a connection
我搜索了一下,发现它需要与 geckodriver 兼容,但问题是,如果我只打开一次浏览器,它就可以正常工作,这对我来说似乎毫无意义。我的脚本如下所示:
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
import csv
import time
options = Options()
driver = webdriver.Firefox()
driver.get('https://buff.163.com/market/goods?goods_id=39968&from=market#tab=selling')
element = driver.find_element_by_xpath('/html/body/div[6]/div/div[5]/table/tbody/tr[2]/td[5]/div[1]/strong')
Price_C9_Col14 = element.text
driver.close()
time.sleep(10)
driver.get('https://buff.163.com/market/goods?goods_id=40086&from=market#tab=selling')
element = driver.find_element_by_xpath('/html/body/div[6]/div/div[5]/table/tbody/tr[2]/td[5]/div[1]/strong')
Price_Epsilon_Col14 = element.text
driver.close()
driver.get('https://buff.163.com/market/goods?goods_id=40151&from=market#tab=selling')
element = driver.find_element_by_xpath('/html/body/div[6]/div/div[5]/table/tbody/tr[2]/td[5]/div[1]/strong')
Price_F3_MLG16 = element.text
driver.close()
driver.get('https://buff.163.com/market/goods?goods_id=40106&from=market#tab=selling')
element = driver.find_element_by_xpath('/html/body/div[6]/div/div[5]/table/tbody/tr[2]/td[5]/div[1]/strong')
Price_Faze_MLG16 = element.text
driver.close()
print(Price_C9_Col14, Price_F3_MLG16, Price_Epsilon_Col14, Price_Faze_MLG16)
最终目标是在无头模式下运行它,但现在我尝试在正常模式下运行它,以找出问题可能是什么。我还检查了以前的答案,但它们很旧,因此兼容版本与我们今天拥有的版本不匹配。我使用 Python 3.9.0,关于 firefox 和 Selenium 版本的 idk,因为我不知道在哪里检查。任何提示/建议表示赞赏
【问题讨论】:
标签: python python-3.x selenium firefox