2016-07-20 1 views
2

У меня есть код, который следует за следующим форматом, как показано ниже. Я пытаюсь использовать xpath для выбора второго абзаца (например, параграф, который начинается: Assisted living - отличный вариант для всех слоев общества ... Учитывая, что div и абзац не имеют простых идентификаторов, я пробовал:Выбор текста с использованием xpath, когда только предшествующие элементы имеют идентификаторы

Я бы подумал, что первая часть //div....29207 ']] будет выбирать div, которому предшествует div с идентификатором 29207. Затем/p [2] выберет его 2-й абзац .

<div id="w_29207" class=" city short-description"> 
<div> 
<p> 
<span itemscope itemtype="http://schema.org/Product"> 
<meta itemprop="name" content="Albuquerque, NM Assisted Living Facilities" />Choose from over 38 Assisted Living communities in Albuquerque, NM and 
<span itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">see 
<meta itemprop="reviewCount" content="360 reviews "/>360 reviews with a 
<meta itemprop="ratingValue" content="4.0 stars out of 5" />4.0 average rating. 
<meta itemprop="description" content="Albuquerque attracts seniors looking for an active senior living experience. The city enjoys four distinct seasons with stunning winters and sunny summers. Seniors in Albuquerque find various cultural outlets and outdoor recreation including an active theater community, festivals, hiking and climbing. " /> We've helped 9,287 families in Albuquerque, NM where Assisted Living ranges from $</span><span itemprop='offerDetails' itemscope itemtype='http://schema.org/AggregateOffer'><span content='1,550' itemprop='lowPrice'>1,550</span> to $<span content='6,100' itemprop='highPrice'>6,100</span>. 
<meta content='USD' itemprop='priceCurrency'> 

</span></span></p> 

<p>Assisted living is a great option for all walks of life. Whether you or a loved has experienced a life changing health diagnosis or you want to shed the burdens of home maintenance from your life, assisted living in Albuquerque could be the perfect match for you. Many seniors in Albuquerque have chosen to transition to assisted living so they can enjoy a sense of community with like-minded neighbors. Another perk of assisted living is for seniors that may need assistance with daily tasks such as, meal preparation, medication management, or help getting to appointments. 
</p> 

+0

Я, пожалуйста, возвращаюсь и принимаю правильные из них и решаю этот вопрос как решение ... :) –

ответ

0

р [2] будет работать, если р элементы двойников.

Некоторые из вариантов:

//*[contains(@class, 'city short-description')]/div/p[2] 
 

 
//*[@class='city short-description']/div/p[2] 
 

 
//div[contains(@class, 'city')]/div/p[2] 
 

 
//div[contains(@id, 'w_')]/div/p[2]

Если вам необходимо вернуть текст, а не элемент добавить/текст() после р [2]

0

Проблема похоже, что второй <div> не является родным братом <div id="w_29207">, это его ребенок (если только вы не разместили HTML-код). Вот почему //div[preceding-sibling::div[@id='w_29207']] не выбирает второй <div>.

Вместо этого, вы можете использовать

//div[@id='w_29207']/div[1]/p[2] 

или любой из вариантов, которые @lauda упоминалось, в зависимости от того, насколько точны вы должны быть об атрибуте ид.

0

Вы можете попробовать следующее xpath, а также: -

//p[not(child::*)] 

или

//p[ancestor::div[@id='w_29207']][2] 

или

//div[@id='w_29207']/descendant::p[2] 

или

//p[ancestor::div[@id='w_29207'] and not(child::*)] 

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

Смежные вопросы