如何通过CSS选择器获取当前元素的所有直接子元素?

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

How to get all direct child elements of current element via CSS Selectors?

问题

I can help you with the translation of the code and the question part. Here is the translated text:

# 我想使用Selenium获取某个特定元素的所有子元素。假设我有以下HTML代码:

    <html>
      <table>
        <tr>
          <td>Test 1</td>
          <td id="123">Test <b>2</b>
            <span>span_text</span>
          </td>
          <td>Test 3</td>
        </tr>
      </table>
    </html>

首先我想通过其id找到第二个td元素然后我想找到其所有子元素即b和span元素)。要找到第二个td元素并不困难

```python
from selenium import webdriver
from selenium.webdriver.common.by import By

page_source = """<table> 
                   <tr>
                        <td>Test 1</td>
                        <td id="123">Test<b>2</b><span>span_text</span></td>
                        <td>Test 3</td>
                   </tr> 
                 </table>
                 """

driver = webdriver.Chrome()
driver.execute_script('document.documentElement.innerHTML=arguments[0]', f"<html>{page_source}</html>")

element = driver.find_element(By.ID, "123")

为了找到子元素,我尝试了td > * CSS选择器:

for elements in element.find_elements(By.CSS_SELECTOR, f"td > *"):
    print(element.tag_name)

但是,这会打印两个td标签,而不是bspan。我还尝试了. > * CSS选择器,但似乎无效。如何在Selenium中使用CSS选择器选择一个WebElement的所有(直接)子元素?

注意:我想使用element.find_elements()方法,即我希望Selenium仅在已找到的元素内进行搜索。


I've translated the code and the question as requested.

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

I&#39;d like to get all child elements of some specific element with Selenium. Let&#39;s say I have the following HTML:

    &lt;html&gt;
      &lt;table&gt;
        &lt;tr&gt;
          &lt;td&gt;Test 1&lt;/td&gt;
          &lt;td id=&quot;123&quot;&gt;Test &lt;b&gt;2&lt;/b&gt;
            &lt;span&gt;span_text&lt;/span&gt;
          &lt;/td&gt;
          &lt;td&gt;Test 3&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/html&gt;

First, I&#39;d like to find the second td element by its id and then I&#39;d like to find all of its child elements (i.e. the b and span elements). Finding the second td element isn&#39;t hard:

```python
from selenium import webdriver
from selenium.webdriver.common.by import By

page_source = &quot;&quot;&quot;&lt;table&gt; 
                   &lt;tr&gt;
                        &lt;td&gt;Test 1&lt;/td&gt;
                        &lt;td id=&quot;123&quot;&gt;Test&lt;b&gt;2&lt;/b&gt;&lt;span&gt;span_text&lt;/span&gt;&lt;/td&gt;
                        &lt;td&gt;Test 3&lt;/td&gt;
                   &lt;/tr&gt; 
                 &lt;/table&gt;
                 &quot;&quot;&quot;

driver = webdriver.Chrome()
driver.execute_script(&#39;document.documentElement.innerHTML=arguments[0]&#39;, f&quot;&lt;html&gt;{page_source}&lt;/html&gt;&quot;)

element = driver.find_element(By.ID, &quot;123&quot;)

In order to find the child elements, I tried the td &gt; * CSS Selector:

for elements in element.find_elements(By.CSS_SELECTOR, f&quot;td &gt; *&quot;):
	print(element.tag_name)

However, this prints two td tags instead of b and span. I also tried the . &gt; * CSS Selector instead, which seems to be invalid. How I can select all (direct) child elements of an WebElement in Selenium by CSS Selectors?

Note: I want to use the element.find_elements() method, i.e. I want selenium to only search within the already found element.

答案1

得分: 1

以下是翻译好的部分:

你差不多已经到位了。你的代码完美无缺。你只需要在每次迭代中保持在 `for` 语句中引用后代为 _`elements`_。因此,你需要调用:

	print(elements.tag_name) # 而不是 element,应该是 elements

下面是完整的程序:

page_source = &quot;&quot;&quot;&lt;table&gt; 
		   &lt;tr&gt;
			&lt;td&gt;Test 1&lt;/td&gt;
			&lt;td id=&quot;123&quot;&gt;Test&lt;b&gt;2&lt;/b&gt;&lt;span&gt;span_text&lt;/span&gt;&lt;/td&gt;
			&lt;td&gt;Test 3&lt;/td&gt;
		   &lt;/tr&gt; 
		 &lt;/table&gt;
		 &quot;&quot;&quot;

driver = webdriver.Chrome(service=s, options=options)
driver.execute_script(&#39;document.documentElement.innerHTML=arguments[0]&#39;, f&quot;&lt;html&gt;{page_source}&lt;/html&gt;&quot;)
element = driver.find_element(By.ID, &quot;123&quot;)
for elements in element.find_elements(By.CSS_SELECTOR, f&quot;td &gt; *&quot;):
	print(elements.tag_name)
		
输出:

	b
	span

希望这对你有所帮助。如果有任何其他问题,请随时提出。

英文:

You were almost there. Your code is perfect. You just need to keep a track that within for statement in each iteration the decendants are referred as elements. So you have to invoke:

print(elements.tag_name) # instead of element, it should be elements

Here is the complete program:

page_source = &quot;&quot;&quot;&lt;table&gt; 
		   &lt;tr&gt;
			&lt;td&gt;Test 1&lt;/td&gt;
			&lt;td id=&quot;123&quot;&gt;Test&lt;b&gt;2&lt;/b&gt;&lt;span&gt;span_text&lt;/span&gt;&lt;/td&gt;
			&lt;td&gt;Test 3&lt;/td&gt;
		   &lt;/tr&gt; 
		 &lt;/table&gt;
		 &quot;&quot;&quot;

driver = webdriver.Chrome(service=s, options=options)
driver.execute_script(&#39;document.documentElement.innerHTML=arguments[0]&#39;, f&quot;&lt;html&gt;{page_source}&lt;/html&gt;&quot;)
element = driver.find_element(By.ID, &quot;123&quot;)
for elements in element.find_elements(By.CSS_SELECTOR, f&quot;td &gt; *&quot;):
	print(elements.tag_name)

Output:

b
span

答案2

得分: 1

There's a bug in your code 如何通过CSS选择器获取当前元素的所有直接子元素?

for elements in element.find_elements(By.CSS_SELECTOR, f"td > *"):
print(element.tag_name)
^ elements

This should be elements.tag_name (plural of element) to use the loop variable, elements. Your variable on the previous line is element so you were printing the TD from the previous line twice.

Having said that, you can do this in a single step and simplify your code and save a little time

for element in driver.find_elements(By.CSS_SELECTOR, "[id='123'] > *"):
print(element.tag_name)

英文:

There's a bug in your code 如何通过CSS选择器获取当前元素的所有直接子元素?

for elements in element.find_elements(By.CSS_SELECTOR, f&quot;td &gt; *&quot;):
    print(element.tag_name)
                ^ elements

This should be elements.tag_name (plural of element) to use the loop variable, elements. Your variable on the previous line is element so you were printing the TD from the previous line twice.

Having said that, you can do this in a single step and simplify your code and save a little time

for element in driver.find_elements(By.CSS_SELECTOR, &quot;[id=&#39;123&#39;] &gt; *&quot;):
    print(element.tag_name)

huangapple
  • 本文由 发表于 2023年2月6日 03:29:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75354942.html
匿名

发表评论

匿名网友

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

确定