Как получить текст из неизвестного тега nth childern p с помощью scrapy? - PullRequest
0 голосов
/ 29 апреля 2020

Я пытаюсь получить описание события. но проблема в том, что описание всех событий находится в произвольном теге <p>. Итак, как мы можем получить доступ к этому тегу <p>, чтобы получить его текст?

<div id='main'>
   <div class='templatecontent'>
       <h3>Evening Tide Talk-POSTPONED<img alt="" src="https://assets.speakcdn.com/assets/2204/hj_scope-2020022008493216.jpg" style="margin: 4px 14px; float: right; width: 300px; height: 463px;" /></h3>

       <p><strong>March 25th | 5:45 p.m. </strong></p>

       <p><strong>Dr. Heather Judkins</strong></p>

       <p><strong>University of South Florida St. Petersburg, Department of Biological Sciences</strong></p>

       <p><strong><em>Lessons Learned from Exploring the Deep</em></strong></p>
       <!-- I want to get this Paragraph --!>

       <p>In her talk, Heather will share lessons learned and some unexpected finds from her journeys. Join us as she discusses unique cephalopod adaptations and memorable moments, while also sharing some “giant” findings from her most recent Gulf of Mexico cruise that led to breaking news in June 2019’s New York Times!</p>

       <p><a class="button-primary" href="/eveningtidetalks">Learn More</a></p>

       <p> </p>

       <p> </p>

       <p> </p>

       <hr />
       <h3>Washed Ashore - Art To Save The Sea <img alt="" src="https://assets.speakcdn.com/assets/2204/tfa_washed_ashore_exhibit_priscilla2.png" style="margin: 3px 13px; float: right; width: 300px; height: 300px;" /></h3>

       <p><strong><strong>February 29th - August 31st</strong></strong></p>

       <!-- I want to get this Paragraph --!>
       <p>In honor of the Aquarium's 25th Anniversary celebration, we are proud to host Washed Ashore - Art To Save The Sea from now until the end of August! The nationally acclaimed exhibit artistically showcases the impacts of plastic pollution on oceans, waterways and wildlife. Washed Ashore sculptures have traveled around the country and The Florida Aquarium is showcasing 18 larger than life sculptures of marine life. </p>

       <p><a class="button" href="/washed-ashore">Learn More</a></p>

       <p> </p>

       <hr />
   </div>
</div>

Как вы можете видеть здесь.

1 Ответ

0 голосов
/ 30 апреля 2020

Вам понадобится комбинация оси following-sibilng , чтобы выбрать теги <p> на том же уровне, что и h3, а затем ограничить те, которые соответствуют p, теми, которые имеют text() как непосредственный ребенок. Однако, если просто сделать p[text()], он вернет (более или менее) пустой <p> </p>, что является неоптимальным. Следовательно, добавьте еще одно ограничение с string-length, чтобы оно возвращало только те, которые кажутся "интересными", в результате чего:

def parse(self, response):
    main_div = response.css('#main')
    for h3 in main_div.xpath('.//h3'):
        talk_title = h3.xpath('text()').get()
        talk_summary = h3.xpath('./following-sibling::p[string-length(text()) > 2]/text()').get()

производит:

[
  {
    "talk_title": "Evening Tide Talk-POSTPONED",
    "talk_summary": "In her talk, Heather will share lessons learned and some unexpected finds from her journeys. Join us as she discusses unique cephalopod adaptations and memorable moments, while also sharing some “giant” findings from her most recent Gulf of Mexico cruise that led to breaking news in June 2019’s New York Times!"
  },
  {
    "talk_title": "Washed Ashore - Art To Save The Sea ",
    "talk_summary": "In honor of the Aquarium's 25th Anniversary celebration, we are proud to host Washed Ashore - Art To Save The Sea from now until the end of August! The nationally acclaimed exhibit artistically showcases the impacts of plastic pollution on oceans, waterways and wildlife. Washed Ashore sculptures have traveled around the country and The Florida Aquarium is showcasing 18 larger than life sculptures of marine life. "
  }
]

Ось following-sibling::p говорит, что она соответствует всем <p> элементам, которые находятся на том же уровне в DOM, что и элемент, к которому привязан XPath (<h3> в нашем случае), что дает список 9 <p> теги. Синтаксис p[] XPath говорит о дальнейшем ограничении совпадающих тегов p, которые удовлетворяют некоторому предикату, из которых string-length(text()) > 2 говорит, что длина строки непосредственного текстового дочернего узла должна быть больше 2. Затем из тех, которые соответствуют <p> теги, вернуть первый text дочерний узел

...