ファイルのアップロード
send_keys()
ファイルをアップロードするメソッドを呼び出す
send_keys()
使用シナリオ:
-
input
タグを使用してファイルをアップロードし、type= file
- コード:
element = driver.find_element()
element.send_keys()
from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep
driver = webdriver.Chrome()
element = driver.find_element(By.XPATH, '//*[@id="app"]/div/section/section/main/div/div[2]/div[1]/div/div/div[4]/div[1]/div/div[2]/form/div[9]/div/div[1]/div[1]/div/input')
element.send_keys(r'C:\Users\Olivia\Pictures\300-300\22.gif')
sleep(5)
driver.quit()
ファイルのダウンロード
画像のダウンロード
実装手順
- 画像が存在するページを開く
- ページ上の画像要素を見つけます
element.attribut('属性名')
メソッドを使用してsrc
、画像の保存アドレス URL である属性の属性値を取得します。
- 画像データを取得するメソッドを呼び出します
reqests.get(url)
(画像データはバイナリデータです)、取得したデータがバイナリの場合は必須、reqests.get(url).content
取得したデータがファイル形式の場合は必須ですreqests.get(url).text
- ファイルをローカルに保存する
[例]: Baidu ホームページのロゴ画像をダウンロード
from selenium import webdriver
from selenium.webdriver.common.by import By
import requests
driver = webdriver.Chrome()
driver.get('https:www.baidu.com')
logo_element = driver.find_element(By.ID, 's_lg_img')
logo_url = logo_element.get_attribute('src')
datas = requests.get(logo_url).content
with open(r'E:\123\baidu.png', 'wb') as file:
file.write(datas)
ファイルのダウンロード
例
import os
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
options = webdriver.ChromeOptions()
param = {
'profile.default_content_settings.popups': 0,
'download.default_directory': os.getcwd()
}
options.add_experimental_option('prefs', param)
driver = webdriver.Chrome(options=options)
driver.get('https://pypi.org/project/selenium/#files')
element= driver.find_element(By.LINK_TEXT, 'selenium-4.8.2.tar.gz')
element.click()
sleep(3)
driver.quit()