2014-02-08 2 views
1

Я очищаю веб-страницы с очень полезным пакетом XML в Р. Я начинаю с XPath, и я изучил его основы из w3 schools website. Я хотел выбрать узел с атрибутом, который имеет значение переменной, и в настоящее время я не могу сделать это эффективно. Ниже показан мой код и проблема встречается:Использование XPath в XML для замены узлов с различными значениями

require(XML) 
myUrl<- "http://www.expatforum.com/expats/uae-expat-forum-expats-living-uae/336985-visa-overstay.html" 
extracted<- htmlParse(myUrl) 
#This parses the HTML data, and a snippet from it is shown as follows 

<td class="alt1" id="td_post_3081025"> 

<!-- message, attachments, sig --> 




     <!-- icon and title --> 
     <div class="smallfont"> 
      <img class="inlineimg" src="http://www.expatforum.com/expats/images/icons/icon8.gif" alt="Angry" border="0" /> 
      <strong>Visa Overstay</strong> 
     </div> 
     <hr size="1" style="color:#068200; background-color:#068200" /> 
     <!--/icon and title --> 


    <!-- message --> 
    <div id="post_message_3081025"> 

     Looking for advice for a complicated situation. I am currently in the UAE working as a teacher with a valid visa. My boyfriend has been living here for 10 years with a valid visa until 2013. There was a discrepency between him and his sponsor ($$$) and his visa was canceled without his knowledge.He was called into the police stattion without even knowing that there was an issue with his visa. He went willingly because he had nothing to hide. He was arrested and jailed for about a month then told he had 3 months to &quot;fix&quot; his problem. The issue has been in the labor courts since then and he is currently living here without a visa (for over a year now). He has called his sponsor and gone to the ministry of labor countless times and no one gives him a direct answer about what he can do to get the block off of his name but no one has arrested him since the initial incident. His sponsor says that he no longer cares and that he would take the block off his name but it is already in the labor courts so there's technically nothing they can do. He wants to turn himself in so that he can pay the overstay charges or do jail time and either reapply for another visa or go somewhere else but is country of origin is Syria and he is scared that they will send him there without any other safe options. Would someone be able to choose where they fly after facing overstay jail time? Is this criteria for deportation and the inability to reapply for another visa here in the UAE? Does anyone know how this process works? It's a scary situation and he needs it to be resolved so that he can begin living his life again. 
    </div> 
    <!--/message --> 

Теперь, я хотел, чтобы извлечь данные, относящиеся к сообщению, заключенного в <div id="post_message_3081025"> тега. Может показаться, что это можно легко достичь, используя //div[@id]. Однако в полном файле есть и другие узлы и атрибуты, которые являются «div id».

Единственное решение, которое я думал, это как-то выбрать значение атрибута id. Но опять же, численная часть этого значения меняется. Я попытался использовать //div[@id='post_message_*'], но это не сработало.

В настоящее время, я принял более длинный, менее эффективный подход преобразования этих данных с as(x,"character"), используя grepl("^div id='post_message'",x), а затем с помощью gsub(), чтобы удалить ненужные биты.

Но есть ли лучший подход, пожалуйста?

Спасибо за ваше время.

ответ

1

Вы можете использовать starts-with

//div[starts-with(@id, "post_message")] 
+0

Ох! Дорогой я, такое легкое решение, и на той же странице я связался! Я должен был прочитать его более подробно, мой плохой ... Большое спасибо! –

+1

Не беспокойтесь. На самом деле, w3schools - это другой сайт, чем w3.org. Страница w3.org, с которой я связан, относится к официальной спецификации XPath 1.0. – unutbu

+0

А, да, я только что проверил! Еще раз спасибо за то, что вы просветили меня на XPath в дополнение к простому предоставлению ответа! –

1

Я добавляю еще один ответ на основе selectr пакет, который позволяет один для запроса HTML-документов с использованием CSS селекторы в отличие от XPath. Я считаю, что css-селекторов легче grep.

library(selectr) 
querySelector(extracted, 'div[id^=post_message]') 

Мы ищем дивы, идентификатор начинается с post_message.

+0

Спасибо, что указали мне на 'selectr', проф. Рамнатх! Всегда интересно узнать о дополнительных инструментах запросов. –

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