我想开发一个应用程序,可以从
Skyscanner
收集特定日期期间某些目的地的最便宜机票。
请求没有问题,因为 Skyscanner
接收了 Get 中的所有搜索数据。例如:
在页面上,我们看到显示最便宜价格的字段。但是,此信息不存在于 HTML 中。这要么是通过 JS 输出的,要么是我粗心,没有在 HTML 中找到它。
由于有动态内容,我决定使用
Selenium
。
我使用我设法找到的指南编写了代码。但是,在 webdriver 初始化期间,我收到错误:
Traceback (most recent call last):
File "C:\Skyscanner\skyscanner.py", line 21, in <module>
driver = webdriver.Chrome(driver_path, chrome_options)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Skyscanner\Lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 45, in __init__
super().__init__(
File "C:\Skyscanner\Lib\site-packages\selenium\webdriver\chromium\webdriver.py", line 50, in __init__
if finder.get_browser_path():
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Skyscanner\Lib\site-packages\selenium\webdriver\common\driver_finder.py", line 47, in get_browser_path
return self._binary_paths()["browser_path"]
^^^^^^^^^^^^^^^^^^^^
File "C:\Skyscanner\Lib\site-packages\selenium\webdriver\common\driver_finder.py", line 56, in _binary_paths
browser = self._options.capabilities["browserName"]
^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'str' object has no attribute 'capabilities'
这是我的代码。请给我一些关于如何解决此问题并实现我的目标的提示?
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
chrome_options = Options()
chrome_options.add_argument("--headless") # Runs Chrome in headless mode.
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
driver_path = 'C:\\chrome-win64\\chrome.exe'
url = 'https://www.skyscanner.net/transport/flights/lond/mnl/240504/?adultsv2=1&cabinclass=economy&childrenv2=&inboundaltsenabled=false&outboundaltsenabled=false&preferdirects=false&ref=home&rtn=0'
driver = webdriver.Chrome(driver_path, chrome_options)
try:
driver.get(url)
time.sleep(20)
cheapest_flight = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, "//div[contains(@class, 'FlightCard_price')]"))
)
print(f"Cheapest Flight Price: {cheapest_flight.text}")
finally:
driver.quit()
chrome.exe
是一个网络浏览器,但driver_path
需要特殊程序将Selenium与浏览器连接起来 - 对于chrome
来说,它是文件chromedriver.exe
您可以在 chromedriver.chromium.org 上找到
对于网络浏览器
Firefox
,您需要 geckodriver.exe
,对于 Microsoft Edge
,您需要 msedgedriver.exe
- 并且您必须在不同的网页上搜索它们。
但是...带有
driver_path
的字符串在 Selenium
的旧版本中使用。在较新的版本中,您必须将类 Service(...)
与此路径一起使用
webdriver.Chrome(service=Service(...), ...)
甚至还有特殊模块
webdriver_manager
,您可以在Service
中使用它,它会检查您是否有驱动程序,最终会下载正确的版本。
但是......在最新版本的
Selenium
中你不需要它,因为它会检查驱动程序并自动下载。
所以你可能只需要
driver = webdriver.Chrome(options=chrome_options)