I want to run Firefox headless using Selenium WebDriver in Python.
The point is to go to a page, wait till JavaScript is loaded, and collect all the links on this page.
To start testing, I did this code:
import time
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
options = Options()
options.add_argument("--headless")
url = "http://localhost:3000/"
driver = webdriver.Firefox(firefox_options=options)
driver.get(url)
time.sleep(5)
urls = driver.find_elements_by_tag_name('a')
print(urls)
driver.quit()
This always gives the following error:
Traceback (most recent call last):
File "sel.py", line 18, in <module>
urls = driver.find_elements_by_tag_name('a')
File "/home/.local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 545, in find_elements_by_tag_name
return self.find_elements(by=By.TAG_NAME, value=name)
File "/home/.local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 995, in find_elements
'value': value})['value'] or []
File "/home/.local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 318, in execute
response = self.command_executor.execute(driver_command, params)
File "/home/petra/.local/lib/python2.7/site-packages/selenium/webdriver/remote/remote_connection.py", line 472, in execute
return self._request(command_info[0], url, body=data)
File "/home/petra/.local/lib/python2.7/site-packages/selenium/webdriver/remote/remote_connection.py", line 496, in _request
resp = self._conn.getresponse()
File "/usr/lib/python2.7/httplib.py", line 1136, in getresponse
response.begin()
File "/usr/lib/python2.7/httplib.py", line 453, in begin
version, status, reason = self._read_status()
File "/usr/lib/python2.7/httplib.py", line 417, in _read_status
raise BadStatusLine(line)
httplib.BadStatusLine: ''
I tried removing this line time.sleep(5)
cause I assumed it might be the problem.
Now print(urls)
returns the following:
[<selenium.webdriver.firefox.webelement.FirefoxWebElement (session="27257d43-81ec-48e4-9ed2-55709a23d60f", element="e728d5ef-001f-4335-bd57-19a1f2d82683")>, <selenium.webdriver.firefox.webelement.FirefoxWebElement (session="27257d43-81ec-48e4-9ed2-55709a23d60f", element="2c59c828-8557-48cc-a79a-02ea3c9d2d65")>, <selenium.webdriver.firefox.webelement.FirefoxWebElement (session="27257d43-81ec-48e4-9ed2-55709a23d60f", element="e2058a00-9bad-4f0c-8e2d-a236a567dddd")>]
This output appears if I put time.sleep(0)
till time.sleep(4)
.
Either way, this is not the output I want; I want to see all the anchors on my page.
What am I doing wrong?
Sorry, I am new to this.