英文:
How to click a Checkbox by driver.find_element(id in Python
问题
我正在尝试自动化我的注册/登录工作。
我的问题是我无法“点击”复选框以接受“使用条款”。
网站的HTML代码:
```html
<div class="formList-content"><label class="checkbox checkbox--brand ">
<input class="input checkbox-input" name="termsConditionsAndPrivacy"
id="registerForm-termsConditionsAndPrivacy" data-handler="focus-toggle"
data-focus-toggle="{"toggles":[{"className":"input-wrapper--focus","target":".formList-row/.input-wrapper"}]}"
type="checkbox"><span class="tGrid-cell tGrid-cell--shrink">
<span class="checkbox-box flex--inline boxAlign-jc--all-c boxAlign-ai--all-c">
<svg width="18px" height="14px" class="icon icon--tick text--color-brandPrimary checkbox-tick">
<use xlink:href="/assets/img/ico_ca8e3.svg#tick"></use></svg></span></span>
<span class="checkbox-text tGrid-cell space--l-2 space--t-0 vAlign--all-m mute--text">Ich habe die AGB <a class="link" href="/regeln-und-bedingungen" rel="nofollow" target="_blank">Regeln und Bedingungen
</a> sowie die <a class="link" href="/datenschutz" rel="nofollow" target="_blank">Datenschutzerklärung</a> gelesen und akzeptiert.</span></label></div>
我尝试的代码如下:
driver.find_element(id, "registerForm-termsConditionsAndPrivacy").click()
导致我得到以下错误:
Traceback (most recent call last):
File "C:\Users\Admin\PycharmProjects\Bot 2\main.py", line 17, in <module>
driver.find_element(id, "registerForm-termsConditionsAndPrivacy").click()
File "C:\Users\Admin\PycharmProjects\Bot 2\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 740, in find_element
return self.execute(Command.FIND_ELEMENT, {"using": by, "value": value})["value"]
File "C:\Users\Admin\PycharmProjects\Bot 2\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 344, in execute
response = self.command_executor.execute(driver_command, params)
File "C:\Users\Admin\PycharmProjects\Bot 2\venv\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 288, in execute
data = utils.dump_json(params)
File "C:\Users\Admin\PycharmProjects\Bot 2\venv\lib\site-packages\selenium\webdriver\remote\utils.py", line 24, in dump_json
return json.dumps(json_struct)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\json\__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type builtin_function_or_method is not JSON serializable
Process finished with exit code 1
如何使其点击TOS复选框?
尝试使用driver.find_element(id, "registerForm-termsConditionsAndPrivacy").click()
。
<details>
<summary>英文:</summary>
I am trying to automate my register/login work.
My problem is that I cannot "click" the Checkbox to accept the "Terms of use"
HTML Code of the Website:
<div class="formList-content"><label class="checkbox checkbox--brand ">
<input class="input checkbox-input" name="termsConditionsAndPrivacy"
id="registerForm-termsConditionsAndPrivacy" data-handler="focus-toggle"
data-focus-toggle="{"toggles":[{"className":"input-wrapper--focus","target":".formList-row/.input-wrapper"}]}"
type="checkbox"><span class="tGrid-cell tGrid-cell--shrink">
<span class="checkbox-box flex--inline boxAlign-jc--all-c boxAlign-ai--all-c">
<svg width="18px" height="14px" class="icon icon--tick text--color-brandPrimary checkbox-tick">
<use xlink:href="/assets/img/ico_ca8e3.svg#tick"></use></svg></span></span>
<span class="checkbox-text tGrid-cell space--l-2 space--t-0 vAlign--all-m mute--text">Ich habe die AGB <a class="link" href="/regeln-und-bedingungen" rel="nofollow" target="_blank">Regeln und Bedingungen
</a> sowie die <a class="link" href="/datenschutz" rel="nofollow" target="_blank">Datenschutzerklärung</a> gelesen und akzeptiert.</span></label></div>
The code I tried ↓
driver.find_element(id, "registerForm-termsConditionsAndPrivacy").click()
**got me this error:**
Traceback (most recent call last):
File "C:\Users\Admin\PycharmProjects\Bot 2\main.py", line 17, in <module>
driver.find_element(id, "registerForm-termsConditionsAndPrivacy").click()
File "C:\Users\Admin\PycharmProjects\Bot 2\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 740, in find_element
return self.execute(Command.FIND_ELEMENT, {"using": by, "value": value})["value"]
File "C:\Users\Admin\PycharmProjects\Bot 2\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 344, in execute
response = self.command_executor.execute(driver_command, params)
File "C:\Users\Admin\PycharmProjects\Bot 2\venv\lib\site-packages\selenium\webdriver\remote\remote_connection.py", line 288, in execute
data = utils.dump_json(params)
File "C:\Users\Admin\PycharmProjects\Bot 2\venv\lib\site-packages\selenium\webdriver\remote\utils.py", line 24, in dump_json
return json.dumps(json_struct)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\json_init_.py", line 231, in dumps
return _default_encoder.encode(obj)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.class.name} '
TypeError: Object of type builtin_function_or_method is not JSON serializable
Process finished with exit code 1
How do I make it click the TOS Checkbox ?
Tried using "driver.find_element(id, "registerForm-termsConditionsAndPrivacy").click()"
</details>
# 答案1
**得分**: 0
不能直接将id作为参数传递。您应该导入'By'并按以下方式使用它。
更新:添加等待元素可点击
```python
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(driver, 10) # 等待最多10秒
element = wait.until(EC.element_to_be_clickable((By.ID, "registerForm-termsConditionsAndPrivacy")))
element.click()
英文:
You cannot pass id directly as argument. You should import 'By' and use it as following.
Update : added wait for element to be clickable
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(driver, 10) # Wait for a maximum of 10 seconds
element = wait.until(EC.element_to_be_clickable((By.ID, "registerForm-termsConditionsAndPrivacy")))
element.click()
答案2
得分: 0
你正在尝试通过实际的ID查找元素,而不是指定参数 'By.ID'。如果你想再次使用该元素,我将其设置为tempVariable
尝试:
tempVariable = driver.find_element(By.ID, "registerForm-termsConditionsAndPrivacy").click()
看看是否解决了你的问题。
英文:
You are trying to find the element by an actual ID instead of specifying the argument 'By.ID'. In case you want to use the element again, I set it to a tempVariable
try,
tempVariable = driver.find_element('By.ID', "registerForm-termsConditionsAndPrivacy").click()
and see if that fixes your problem
答案3
得分: 0
以下是已翻译好的部分:
这是您可以尝试的方法:
```python
import time
from selenium.webdriver import Chrome
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
import selenium.webdriver.support.expected_conditions as EC
driver = Chrome()
driver.get("https://www.mydealz.de/register")
wait = WebDriverWait(driver, 10)
# accept all cookies
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'button[data-t="acceptAllBtn"]'))).click()
checkboxes = driver.find_elements(By.CSS_SELECTOR, 'span.tGrid-cell.tGrid-cell--shrink')
# select the 2nd checkbox
checkboxes[1].click()
time.sleep(2)
同样,您也可以使用checkboxes[0].click()
选择第一个复选框。
希望这能解决您的问题。
<details>
<summary>英文:</summary>
Here's how you may try:
```python
import time
from selenium.webdriver import Chrome
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
import selenium.webdriver.support.expected_conditions as EC
driver = Chrome()
driver.get("https://www.mydealz.de/register")
wait = WebDriverWait(driver, 10)
# accept all cookies
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'button[data-t="acceptAllBtn"]'))).click()
checkboxes = driver.find_elements(By.CSS_SELECTOR, 'span.tGrid-cell.tGrid-cell--shrink')
# select the 2nd checkbox
checkboxes[1].click()
time.sleep(2)
Similarly, you can also select the 1st checkbox using checkboxes[0].click()
I hope this solves your problem.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论