我正在使用 selenium 和 python 来单击网页上的按钮。这会将 csv 格式的数据复制到剪贴板上。然后我使用剪贴板上的数据创建一个数组,在程序中进一步使用。一切正常,直到我以无头模式启动 webdriver。有什么解决办法吗?整个代码可以在没有硒的情况下编写吗?我对代码中的想法和改进持开放态度。
try:
objFFOptions = Options()
objFFOptions.add_argument('--headless')
objFFWebDriver = webdriver.Firefox(options= objFFOptions ) # start hidden
#objFFWebDriver = webdriver.Firefox()
except:
print("Error in initiating the Firefox webdriver")
objFFWebDriver.quit()
quit()
try:
objFFWebDriver.get("https://chartink.com/screener/90dis")
except:
print("Error in opening the webpage")
objFFWebDriver.quit()
quit()
# loop for waiting before query data loads
intAttemptCounter = 0
boolStockDataFetched = False
while True:
intAttemptCounter = intAttemptCounter + 1
print("\tFetching attempt ", intAttemptCounter)
try:
objFilterMessageElement = WebDriverWait(objFFWebDriver, (intDelaySeconds * intAttemptCounter)). \
until(expected_conditions.presence_of_element_located((By.ID, 'DataTables_Table_0_info')) or \
expected_conditions.presence_of_element_located((By.CLASS_NAME, 'dataTables_empty')))
print("\tEither of the two marker elements found")
if re.search(r"Filtered\s+[0-9]+\s+stocks\s+\([0-9]+\s+to\s+[0-9]+\)",
objFilterMessageElement.text) is not None:
print("\t",objFilterMessageElement)
try:
# click copy button
objFFWebDriver.find_element(By.XPATH, \
"//*[@class='btn btn-default buttons-copy buttons-html5 btn-primary']").click()
except NoSuchElementException:
if intAttemptCounter <= intMaxAttempt:
continue
# store the query result from clipboard to a string
strCSVData = pyperclip.paste()
pyperclip.copy("")
# create array from the csv string containing stock data
arrDataList = list(csv.reader(StringIO(strCSVData),delimiter='\t'))
arrFinalDataList = [arrDataRecord[2] for arrDataRecord in arrDataList[3:]]
boolStockDataFetched = True
break
elif objFilterMessageElement.text == "No stocks filtered in the Scan":
print("\t",objFilterMessageElement.text)
break
else:
if intAttemptCounter <= intMaxAttempt:
continue
except TimeoutException:
print("\tTimeout Exception")
if intAttemptCounter <= intMaxAttempt:
continue
else:
break
if boolStockDataFetched == False:
print("Error in fetching records or no records fetched")
objFFWebDriver.quit()