TimeoutException, когда я запускаю код с Headless Chrome, но код работает нормально в Selenium Webdriver - PullRequest
0 голосов
/ 17 апреля 2020

Я пытаюсь автоматизировать загрузку документов с сайта фонда, используя безголовый chrome. Логика c заключается в том, что я сначала сохраняю список идентификаторов фондов, используя pandas, затем открываю веб-сайт, используя chrome, l oop без заголовка для каждого фонда (перейдите к нужному документу фонда и загрузите его используя запросы).

Я продолжаю получать следующую ошибку всякий раз, когда использую безголовый chrome, но код прекрасно работает без аргумента «безголовый» в Selenium Webdriver.

Сообщение об ошибке выглядит следующим образом:

TimeoutException                          Traceback (most recent call last)
<ipython-input-3-0f710474da89> in <module>
     61 
     62     docFS = WebDriverWait(browser, 20).until(
---> 63         EC.visibility_of_element_located((By.CSS_SELECTOR, "body > div.ng-scope.layout-.fundexplorer-betanoticepanel.fundexplorer-core-clientheaderpanel.desktop.chrome.mac.landscape.ltr.fund-explorer.fx-header-visible.layout-floating.layout-default.client-header-visible.sg.fx-disclaimer-panel-visible.fx-menu-undefined > div.layout-.fundexplorer-betanoticepanel.fundexplorer-core-clientheaderpanel.layout-floating.layout-default > fx-page > div > div > fx-in-depth-profile > div > div > amid-layout > div > span > div > div > div.amid-layout.amid-layout-row.layout-default.fundexplorer-documentspanel.layout-layout3.amid-layout-visible > div > fx-documents-panel > div > div > div:nth-child(1) > div.col-category-document.clearfix.layout-layout3.fundexplorer-documentitem > div > fx-document-item > div > div > a"))
     64     )
     65 

/opt/anaconda3/lib/python3.7/site-packages/selenium/webdriver/support/wait.py in until(self, method, message)
     78             if time.time() > end_time:
     79                 break
---> 80         raise TimeoutException(message, screen, stacktrace)
     81 
     82     def until_not(self, method, message=''):

TimeoutException: Message: 

И это мой полный код в Python для этого:

from selenium import webdriver
import pandas as pd
import numpy as np
import re
import time
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
import requests
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Global Variable declaration
data = pd.read_csv("factsheet.updated.Hemanth - SGP.IPB.csv")        
ISIN=data['ISIN']
name= data['AssetName']
quote_page= "https://www.schroders.com/en/sg/private-investor/fund-centre/prices/"

#headless chrome initiation
chromedriver = '/Users/hemanthj/chromedriver'                                            
options = webdriver.ChromeOptions()
options.add_argument('headless')
# options.add_argument('window-size=1024,600')
# options.add_argument('allow-insecure-localhost')
# options.add_argument('--ignore-certificate-errors')
options.add_experimental_option("prefs", {
        "download.default_directory": "<path_to_download_default_directory>",
        "download.prompt_for_download": False,
        "download.directory_upgrade": True,
        "safebrowsing_for_trusted_sources_enabled": False,
        "safebrowsing.enabled": False 
})
browser = webdriver.Chrome(executable_path=chromedriver, options=options) 


# Website scrolling and download
page = browser.get(quote_page)
browser.set_window_size(1024, 600)
browser.maximize_window()
time.sleep(5)
terms = browser.find_element_by_css_selector('button.btn.disclaimer-accept.btn-primary.btn-lg') 
terms.click()
time.sleep(2)

#Looping through ISIN's
for x in ISIN:
    search_area = browser.find_element_by_id('fund-name')
    search_area.clear()
    time.sleep(1)
    search_area.send_keys(x)
    search_area.send_keys(Keys.ENTER)
    time.sleep(1)

#click on fund if it is available, otherwise skip to next iteration
    fund = browser.find_elements_by_css_selector("#tbl_funds > tbody > tr > td.col_fund_name > a.isin")
    if len(fund) > 0:
         fund[0].click()
    else:
        continue

    docFS = WebDriverWait(browser, 20).until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, "body > div.ng-scope.layout-.fundexplorer-betanoticepanel.fundexplorer-core-clientheaderpanel.desktop.chrome.mac.landscape.ltr.fund-explorer.fx-header-visible.layout-floating.layout-default.client-header-visible.sg.fx-disclaimer-panel-visible.fx-menu-undefined > div.layout-.fundexplorer-betanoticepanel.fundexplorer-core-clientheaderpanel.layout-floating.layout-default > fx-page > div > div > fx-in-depth-profile > div > div > amid-layout > div > span > div > div > div.amid-layout.amid-layout-row.layout-default.fundexplorer-documentspanel.layout-layout3.amid-layout-visible > div > fx-documents-panel > div > div > div:nth-child(1) > div.col-category-document.clearfix.layout-layout3.fundexplorer-documentitem > div > fx-document-item > div > div > a"))
    )


    doc=browser.find_element_by_css_selector('body > div.ng-scope.layout-.fundexplorer-betanoticepanel.fundexplorer-core-clientheaderpanel.desktop.chrome.mac.landscape.ltr.fund-explorer.fx-header-visible.layout-floating.layout-default.client-header-visible.sg.fx-disclaimer-panel-visible.fx-menu-undefined > div.layout-.fundexplorer-betanoticepanel.fundexplorer-core-clientheaderpanel.layout-floating.layout-default > fx-page > div > div > fx-in-depth-profile > div > div > amid-layout > div > span > div > div > div.amid-layout.amid-layout-row.layout-default.fundexplorer-documentspanel.layout-layout3.amid-layout-visible > div > fx-documents-panel > div > div > div:nth-child(1) > div.col-category-document.clearfix.layout-layout3.fundexplorer-documentitem > div > fx-document-item > div > div > a')
    url= doc.get_attribute("_href")
    myfile = requests.get(url)
    open('/Users/hemanthj/Downloads/SGP-IPB Schroders' + x + '.pdf', 'wb').write(myfile.content)
    browser.back()
    time.sleep(2)
    search_clear = driver.find_element_by_id('fund-name').clear()
    time.sleep(2)


browser.quit()

Я попытался добавить контекст менеджер, как и в этой ссылке, но не повезло: https://rollout.io/blog/get-selenium-to-wait-for-page-load/

Какие-нибудь решения?

...