【问题标题】:Retrieve items text inside dropdown list xpath在下拉列表 xpath 中检索项目文本
【发布时间】:2020-05-06 12:48:27
【问题描述】:

我有一个这样的选择

<select name="super_attribute[93]" data-selector="super_attribute[93]" data-validate="{required:true}" id="attribute93" class="super-attribute-select" aria-required="true">
<option value="">Choose an Option...</option>
<option value="131">Green</option>
<option value="20364">Black</option>
<option value="20365">White</option></select>

我想使用 CSS 选择器或 Xpath 从下拉列表(绿色、黑色、白色)中获取项目文本

我尝试了以下

response.xpath("//*[(@id = 'attribute93')]").extract()

由于某种原因,它只返回了第一个值

[u'<select name="super_attribute[93]" data-selector="super_attribute[93]" data-validate="{required:true}" id="attribute93" class="super-attribute-select"><option value="">Choose an Option...</option></select>']

【问题讨论】:

  • 您选择的不是option 元素,而是select 元素。您只在输入文档中显示 one select 元素。你确定你展示的是完整的输出吗?请显示更多您的 Python 代码,以便人们可以运行它。谢谢。

标签: python xpath web-scraping scrapy css-selectors


【解决方案1】:

您选择的不是option 元素,其中有几个,而是select 元素。您只在输入文档中显示 一个 select 元素。

>>> from scrapy.selector import Selector
>>> body = """<select name="super_attribute[93]" data-selector="super_attribute[93]" data-validate="{required:true}" id="attribute93" class="super-attribute-select" aria-required="true">
... <option value="">Choose an Option...</option>
... <option value="131">Green</option>
... <option value="20364">Black</option>
... <option value="20365">White</option></select>"""
>>> response = Selector(text=body)
>>> response.xpath("//*[(@id = 'attribute93')]").extract()
['<select name="super_attribute[93]" data-selector="super_attribute[93]" data-validate="{required:true}" id="attribute93" class="super-attribute-select" aria-required="true">\n<option value="">Choose an Option...</option>\n<option value="131">Green</option>\n<option value="20364">Black</option>\n<option value="20365">White</option></select>']

输出是一个包含一个元素的列表,但它不是您在问题中发布的内容(至少对于scrapy 1.8.0):包括所有子option 元素。

使用来自this existing answer 的正确XPath 表达式:

>>> response.xpath('//select[@id="attribute93"]/option[position()>1]/text()').extract()
['Green', 'Black', 'White']

【讨论】:

    【解决方案2】:

    Xpath:

    //select[@id="attribute93"]/option[position()>1]/text()
    

    【讨论】:

    • response.xpath('//select[@id="attribute93"]/option[position()>1]/text()').extract() ,它返回一个空数组
    【解决方案3】:

    要选择所有 &lt;options&gt;,您的 CSS 查询将是:

    select#attribute93 option
    

    【讨论】:

    • 这对我不起作用,response.xpath('select[name="super_attribute[93]"] option').extract() | ValueError:XPath 错误:select[name="super_attribute[93]"] 选项中的表达式无效
    • 抱歉,我没有意识到 &lt;select&gt; 元素有一个 id - 我已经将 CSS 选择器更新为更简单的东西。试试:select#attribute93 option.
    • 这没有返回错误,但只得到了第一个选项>>> response.css('select#attribute93 option').extract() [u'']
    猜你喜欢
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    • 2014-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    相关资源
    最近更新 更多