首页 > 解决方案 > Selenium 从 WebElement Python 获取文本

问题描述

您好,我想要从我的尺寸 webelement 打印数据

这是网站的 HTML

<div class="size-option"><label class="custom-input type-box size-box">
                            <input class="form-control" type="radio" name="sizeChartId" value="163" data-quantity="4">
                            <span class="checker-box">8</span>
                        </label><label class="custom-input type-box size-box">
                            <input class="form-control" type="radio" name="sizeChartId" value="164" data-quantity="5">
                            <span class="checker-box">8.5</span>
                        </label><label class="custom-input type-box size-box">
                            <input class="form-control" type="radio" name="sizeChartId" value="165" data-quantity="3">
                            <span class="checker-box">9</span>
                        </label><label class="custom-input type-box size-box">
                            <input class="form-control" type="radio" name="sizeChartId" value="167" data-quantity="8">
                            <span class="checker-box">10</span>
                        </label><label class="custom-input type-box size-box">
                            <input class="form-control" type="radio" name="sizeChartId" value="168" data-quantity="5">
                            <span class="checker-box">10.5</span>
                        </label><label class="custom-input type-box size-box">
                            <input class="form-control" type="radio" name="sizeChartId" value="169" data-quantity="3">
                            <span class="checker-box">11</span>
                        </label></div>

print(size.text)给我

AttributeError:“列表”对象没有属性“文本”

这是我的元素 size=driver.find_elements_by_xpath("//*[@id='product']/div[1]/div/div[1]/div[2]/div/div[3]/div")

for value in size:
    print(value.text)

不工作

print(size[0].text)

只要给我空,但我想打印列表中的跨度数字。

标签: pythonseleniumxpathweb-crawler

解决方案


由于“大小”是 Web 元素的列表,如果您希望打印其所有元素的文本值,则必须遍历列表并打印每个元素文本,如下所示:

size=driver.find_elements_by_xpath("//*[@id='product']/div[1]/div/div[1]/div[2]/div/div[3]/div")
for el in size:
    print(el.text)

否则,如果 size 打算成为单个元素,我不知道"//*[@id='product']/div[1]/div/div[1]/div[2]/div/div[3]/div"XPath 的定位是什么 - 如果是这样,你应该使用

size=driver.find_element_by_xpath("//*[@id='product']/div[1]/div/div[1]/div[2]/div/div[3]/div")

代替

size=driver.find_elements_by_xpath("//*[@id='product']/div[1]/div/div[1]/div[2]/div/div[3]/div")

推荐阅读