Python find_element_by_css_selector 定位

丌官子安
2023-12-01

1、通过 id 定位

# HTML
<div id="goods">
    <span id="title"></span>
</div>

# 通过 ID 定位
find_element_by_css_selector("#goods")

# 通过 tag 与 id 组合定位
find_element_by_css_selector("span#title")

# 多层级定位中间用 ">"
find_element_by_css_selector("#goods>#title")

 2、通过 class 定位

# HTML
<div class="goods">
    <span class="title"></span>
</div>

# 通过 class 定位
find_element_by_css_selector(".goods")

3、相同 子元素 nth-child(*) 定位

# HTML
<ul>
    <li>11111</li>
    <li>22222</li>
    <li>33333</li>
</ul>

# 通过nth-chlid(2) 定位到 ul 下 li 中第2个元素 22222
find_element_by_css_selector("ul>li:nth-chlid(2)")

4、 使用 属性 定位

# HTML
<div>
    <input class="title" autocomplete="off">
</div>

# 通过 "[]" 定位 属性为 autocomplete="off" input 标签 
find_element_by_css_selector("[autocomplete='off']")

5、定位技巧

# 可以先通过 get_attribute("innerHTML")方法 打印出相应的内容,来判断定位是否准确
content=find_element_by_css_selector("ul>li:nth-child(2)").get_attribute("innerHTML")
print(content)
 类似资料: