簡體   English   中英

Python Selenium Chromedriver 無法使用 --headless 選項

[英]Python Selenium Chromedriver not working with --headless option

我正在運行 chromedriver 以嘗試從網站上抓取一些數據。 沒有無頭選項,一切正常。 但是,當我添加該選項時,webdriver 需要很長時間才能加載 url,並且當我嘗試查找一個元素(在沒有 --headless 的情況下運行時找到)時,我收到錯誤消息。

使用 print 語句並在 url“加載”后獲取 html,我發現沒有 html,它是空的(見下面的 output)。

class Fidelity:
    def __init__(self):
        self.url = 'https://eresearch.fidelity.com/eresearch/gotoBL/fidelityTopOrders.jhtml'
        self.options = Options()
        self.options.add_argument("--headless")
        self.options.add_argument("--window-size=1500,1000")
        self.driver = webdriver.Chrome(executable_path='.\\dependencies\\chromedriver.exe', options = self.options)
        print("init")

    def initiate_browser(self):
        self.driver.get(self.url)
        time.sleep(5)
        script = self.driver.execute_script("return document.documentElement.outerHTML")
        print(script)
        print("got url")

    def find_orders(self):
        wait = WebDriverWait(self.driver, 15)
        data= wait.until(ec.visibility_of_element_located((By.CSS_SELECTOR, '[id*="t_trigger_TSLA"]'))) #ERROR ON THIS LINE

這是整個 output:

init
<html><head></head><body></body></html>
url
Traceback (most recent call last):
  File "C:\Users\Zachary\Documents\Python\Tesla Stock Info\Scraper.py", line 102, in <module>
    orders = scrape.find_tesla_orders()
  File "C:\Users\Zachary\Documents\Python\Tesla Stock Info\Scraper.py", line 75, in find_tesla_orders
    tesla = self.driver.find_element_by_xpath("//a[@href='https://qr.fidelity.com/embeddedquotes/redirect/research?symbol=TSLA']")
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//a[@href='https://qr.fidelity.com/embeddedquotes/redirect/research?symbol=TSLA']"}
  (Session info: headless chrome=74.0.3729.169)
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows NT 10.0.17763 x86_64)

更新代碼的新錯誤:

init
<html><head></head><body></body></html>
url
Traceback (most recent call last):
  File "C:\Users\Zachary\Documents\Python\Tesla Stock Info\Scraper.py", line 104, in <module>
    orders = scrape.find_tesla_orders()
  File "C:\Users\Zachary\Documents\Python\Tesla Stock Info\Scraper.py", line 76, in find_tesla_orders
    tesla = wait.until(ec.visibility_of_element_located((By.CSS_SELECTOR, '[id*="t_trigger_TSLA"]')))
  File "C:\Program Files (x86)\Python37-32\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: 

我試過通過谷歌找到這個問題的答案,但沒有一個建議有效。 是否有其他人在某些網站上遇到此問題? 任何幫助表示贊賞。

更新

不幸的是,這個腳本仍然無法運行,webdriver 在無頭時由於某種原因沒有正確加載頁面,即使在沒有使用無頭選項運行它的情況下一切正常。

對於將來想解決此問題的任何人來說,某些網站只是無法使用 chrome 的無頭選項正確加載。 我認為沒有辦法解決這個問題。 只需使用不同的瀏覽器(如 Firefox)。 感謝 user8426627 為此。

您是否嘗試過使用用戶代理?

我遇到了同樣的錯誤。 首先我做的是下載無頭和普通的 HTML 源頁面:

html = driver.page_source
file = open("foo.html","w")
file.write(html)
file.close()

無頭模式的 HTML 源代碼是一個簡短的文件,幾乎在末尾有一行: The page cannot be displayed. Please contact the administrator for additional information. The page cannot be displayed. Please contact the administrator for additional information. 但正常模式是預期的 HTML。

我通過添加用戶代理解決了這個問題:

from fake_useragent import UserAgent
user_agent = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.2 (KHTML, like Gecko) Chrome/22.0.1216.0 Safari/537.2'
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument(f'user-agent={user_agent}')
driver = webdriver.Chrome(executable_path = f"your_path",chrome_options=chrome_options)

添加顯式等待。 您還應該使用另一個定位器,當前定位器匹配 3 個元素。 該元素具有唯一的 id 屬性

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import By

wait = WebDriverWait(self.driver, timeout)
data = wait.until(ec.visibility_of_element_located((By.CSS_SELECTOR, '[id*="t_trigger_TSLA"]')))

我需要在不離開Goog​​le瀏覽器的情況下從同一控制台運行腳本,但是瀏覽器仍與我的程序一起運行

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("window-size=1920,1080")
print("complete")

driver = webdriver.Chrome('C:\proyectos\python-selenium\driver\chromedriver.exe')
driver.get('https://www.facebook.com/')

嘗試設置 window 大小以及無頭。 添加這個:

chromeOptions.add_argument("--window-size=1920,1080")

無頭瀏覽器的默認大小很小。 如果代碼在未啟用無頭時有效,則可能是因為您的 object 位於 window 之外。

有些網站無法使用 Chrome 的無頭選項正確加載。

前面的說法其實是錯誤的。 我剛遇到這個問題,Chrome 沒有檢測到這些元素。 當我看到@LuckyZakary 的回答時,我感到很震驚,因為有人用nodeJs為同一個網站創建了一個報廢,但沒有收到這個錯誤。

@AtulGumar 回答對 Windows 有幫助,但在 Ubuntu 服務器上它失敗了。 所以這還不夠。 讀完這篇文章后,歸根結底,@AtulGumar 錯過的是添加–disable-gpu標志。

所以它在 Windows 和 Ubuntu 服務器上對我有用,沒有帶有這些選項的 GUI:

webOptions = webdriver.ChromeOptions()
webOptions.headless = True
webOptions.add_argument("--window-size=1920,1080")
webOptions.add_argument("–disable-gpu")
driver = webdriver.Chrome(options=webOptions)

我還按照此處的建議安裝了xvfb和其他軟件包:

sudo apt-get -y install xorg xvfb gtk2-engines-pixbuf
sudo apt-get -y install dbus-x11 xfonts-base xfonts-100dpi xfonts-75dpi xfonts-cyrillic xfonts-scalable

並執行:

Xvfb -ac :99 -screen 0 1280x1024x16 &
export DISPLAY=:99

強文本嘗試將可執行路徑添加到服務 object

options =  Options()
options.add_argument('---incognito')
options.add_argument('---disable-extension')
options.add_argument("--no-sandbox")
options.add_argument('-–disable-gpu')
options.add_argument('--headless')
service = Service (executable_path=ChromeDriverManager().install() )
return webdriver.Chrome(service=service  , options=options)

它對我有用:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM