Как получить второе значение этого xpath? - PullRequest
0 голосов
/ 07 августа 2020

Ниже html.

<div class="list-items tab-pane fade active show" ng-class="type=='pay'?'show active':''" tabindex="1" id="pay-bills">

    <div ng-repeat="item in BillList.Result.categorizedBillNickBene" class="ng-scope">
        <h2 class="head ng-binding" ng-show="filtered.length!=0">Electricity Bill Payment</h2>
    </div>

    <div ng-repeat="item in BillList.Result.categorizedBillNickBene" class="ng-scope">
        <h2 class="head ng-binding" ng-show="filtered.length!=0">Gas Bill Payment</h2>
    </div>

</div>

Я хочу получить второе значение h2, то есть «Оплата счета за газ». Я написал xpath как

//div[@id='pay-bills']//div//h2[@class='head ng-binding'][2]

Проблема в том, что я не могу получить второе значение с помощью «[2]». хотя, когда я вставляю «[1]», я получаю два значения.

Ответы [ 3 ]

1 голос
/ 07 августа 2020

Почему это не работает:

//div[@id='pay-bills']//div//h2[@class='head ng-binding'][2]

Вы ищете элемент h2 с позицией, равной 2. Все элементы h2 в ваших демонстрационных данных находятся на первом месте (1 ) position.

Вы можете использовать решение, предложенное @chrisis, или go с:

(//div[@id='pay-bills']/div/h2)[2]/text()

Используйте (), чтобы указать, что вы хотите, чтобы второй отображаемый результат XPath был заключен by ().

Не забудьте также удалить ненужные // из выражения (должно быть /, поскольку вторые div и h2 являются дочерними элементами).

0 голосов
/ 07 августа 2020

Вам нужен второй div, то, что вы пробовали, дало бы вам второй h2 внутри div, если бы он был. Попробуйте

//div[@id='pay-bills']//div[2]//h2[@class='head ng-binding']
0 голосов
/ 07 августа 2020

Надеюсь, это поможет.

>>> html = """ <div class="list-items tab-pane fade active show" ng-class="type=='pay'?'show active':''" tabindex="1" id="pay-bills"
... > 
...  
...     <div ng-repeat="item in BillList.Result.categorizedBillNickBene" class="ng-scope"> 
...         <h2 class="head ng-binding" ng-show="filtered.length!=0">Electricity Bill Payment</h2> 
...     </div> 
...  
...     <div ng-repeat="item in BillList.Result.categorizedBillNickBene" class="ng-scope"> 
...         <h2 class="head ng-binding" ng-show="filtered.length!=0">Gas Bill Payment</h2> 
...     </div> 
...  
... </div>"""                                                                                                                       

>>> html                                                                                                                            
' <div class="list-items tab-pane fade active show" ng-class="type==\'pay\'?\'show active\':\'\'" tabindex="1" id="pay-bills">\n\n    <div ng-repeat="item in BillList.Result.categorizedBillNickBene" class="ng-scope">\n        <h2 class="head ng-binding" ng-show="filtered.length!=0">Electricity Bill Payment</h2>\n    </div>\n\n    <div ng-repeat="item in BillList.Result.categorizedBillNickBene" class="ng-scope">\n        <h2 class="head ng-binding" ng-show="filtered.length!=0">Gas Bill Payment</h2>\n    </div>\n\n</div>'


>>> from pprint import pprint                                                                                                       

>>> pprint(html)                                                                                                                    
(' <div class="list-items tab-pane fade active show" '
 'ng-class="type==\'pay\'?\'show active\':\'\'" tabindex="1" id="pay-bills">\n'
 '\n'
 '    <div ng-repeat="item in BillList.Result.categorizedBillNickBene" '
 'class="ng-scope">\n'
 '        <h2 class="head ng-binding" ng-show="filtered.length!=0">Electricity '
 'Bill Payment</h2>\n'
 '    </div>\n'
 '\n'
 '    <div ng-repeat="item in BillList.Result.categorizedBillNickBene" '
 'class="ng-scope">\n'
 '        <h2 class="head ng-binding" ng-show="filtered.length!=0">Gas Bill '
 'Payment</h2>\n'
 '    </div>\n'
 '\n'
 '</div>')

>>> from scrapy.http import HtmlResponse                                                                                            

>>> response = HtmlResponse(url='my html string', body=html, encoding='utf-8')                                                      

>>> response.xpath('//div')                                                                                                         
[<Selector xpath='//div' data='<div class="list-items tab-pane fade ...'>, <Selector xpath='//div' data='<div ng-repeat="item in BillList.Resu...'>, <Selector xpath='//div' data='<div ng-repeat="item in BillList.Resu...'>]


>>> response.xpath('//div').getall()                                                                                                
['<div class="list-items tab-pane fade active show" ng-class="type==\'pay\'?\'show active\':\'\'" tabindex="1" id="pay-bills">\n\n    <div ng-repeat="item in BillList.Result.categorizedBillNickBene" class="ng-scope">\n        <h2 class="head ng-binding" ng-show="filtered.length!=0">Electricity Bill Payment</h2>\n    </div>\n\n    <div ng-repeat="item in BillList.Result.categorizedBillNickBene" class="ng-scope">\n        <h2 class="head ng-binding" ng-show="filtered.length!=0">Gas Bill Payment</h2>\n    </div>\n\n</div>', '<div ng-repeat="item in BillList.Result.categorizedBillNickBene" class="ng-scope">\n        <h2 class="head ng-binding" ng-show="filtered.length!=0">Electricity Bill Payment</h2>\n    </div>', '<div ng-repeat="item in BillList.Result.categorizedBillNickBene" class="ng-scope">\n        <h2 class="head ng-binding" ng-show="filtered.length!=0">Gas Bill Payment</h2>\n    </div>']


>>> response.xpath('//div//h2').getall()                                                                                            
['<h2 class="head ng-binding" ng-show="filtered.length!=0">Electricity Bill Payment</h2>', '<h2 class="head ng-binding" ng-show="filtered.length!=0">Gas Bill Payment</h2>']


>>> response.xpath('//div//h2').getall()[1]                                                                                         
'<h2 class="head ng-binding" ng-show="filtered.length!=0">Gas Bill Payment</h2>'


>>> response.xpath('//div//h2/text()').getall()[1]                                                                                  
'Gas Bill Payment'
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...