简体   繁体   中英

How to change Default Camera of ChromeDriver when web scraping with Selenium (Python)?

I am using Selenium (with Python on Mac) to web scrape a site that requires my camera.

However, I do not want to use my Computer Camera, I would like to use a Virtual Camera (of the OBS Application).

At the beginning, my first problem was allowing the ChromeDriver to use the camera, as the pop-up of permission was appearing. I solved this problem with this code:

options = webdriver.ChromeOptions()
options.add_experimental_option("prefs", { \
    "profile.default_content_setting_values.media_stream_mic": 1,     # 1:allow, 2:block 
    "profile.default_content_setting_values.media_stream_camera": 1,  # 1:allow, 2:block 
    "profile.default_content_setting_values.geolocation": 2,          # 1:allow, 2:block 
    "profile.default_content_setting_values.notifications": 2         # 1:allow, 2:block 
})

In this way, it is using my default camera. I would like to add something like "profile.default_content_setting_values.media_stream_camera.option": "OBS", in the code above, but that is not quite right. I read that the Preferences.json file located at /Users/myusername/Library/Application Support/Google/Chrome/Default/Preferences.json can show what can be changed in the above prefs dictionary, but I do not understand it very well.

As I am unable tho proceed, any help would be of great value.

You could go to the Chrome camera settings when starting the script and change the default camera:

config_camera_url = "chrome://settings/content/camera"
driver.get(config_camera_url)
sleep(3)  # Wait until selector appears
selector = driver.execute_script(
    "return document.querySelector('settings-ui')"
    ".shadowRoot.querySelector('settings-main')"
    ".shadowRoot.querySelector('settings-basic-page')"
    ".shadowRoot.querySelector('settings-section > settings-privacy-page')"
    ".shadowRoot.querySelector('settings-animated-pages > settings-subpage > media-picker')"
    ".shadowRoot.querySelector('#picker > #mediaPicker')"
    ".value = 'OBS-Camera4'"  # Change for your default camera
)

Due to Selenium doesn't provide support to interact with Shadow DOM elements, you need to go through each shadow-root elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM