点击复选框的方法:通过 `driver.find_element` 在 Python 中找到元素的 ID。

huangapple go评论60阅读模式
英文:

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 &quot;click&quot; the Checkbox to accept the &quot;Terms of use&quot;

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="{&quot;toggles&quot;:[{&quot;className&quot;:&quot;input-wrapper--focus&quot;,&quot;target&quot;:&quot;.formList-row/.input-wrapper&quot;}]}"

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 &quot;driver.find_element(id, &quot;registerForm-termsConditionsAndPrivacy&quot;).click()&quot;

</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, &quot;registerForm-termsConditionsAndPrivacy&quot;)))
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(&#39;By.ID&#39;, &quot;registerForm-termsConditionsAndPrivacy&quot;).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)

点击复选框的方法:通过 `driver.find_element` 在 Python 中找到元素的 ID。

同样,您也可以使用checkboxes[0].click()选择第一个复选框。

希望这能解决您的问题。


<details>
<summary>英文:</summary>

Here&#39;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(&quot;https://www.mydealz.de/register&quot;)
wait = WebDriverWait(driver, 10)

# accept all cookies
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, &#39;button[data-t=&quot;acceptAllBtn&quot;]&#39;))).click()

checkboxes = driver.find_elements(By.CSS_SELECTOR, &#39;span.tGrid-cell.tGrid-cell--shrink&#39;)
# select the 2nd checkbox
checkboxes[1].click()

time.sleep(2)

点击复选框的方法:通过 `driver.find_element` 在 Python 中找到元素的 ID。

Similarly, you can also select the 1st checkbox using checkboxes[0].click()

I hope this solves your problem.

huangapple
  • 本文由 发表于 2023年6月12日 10:45:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76453368.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定