使用XPath提取HTML结果失败,因为内容是动态加载的

2024-10-02 10:34:19 发布

您现在位置:Python中文网/ 问答频道 /正文

与我前面的一个问题Extracting p within h1 with Python/Scrapy相关但不同的是,我遇到了一种情况,即scray(对于Python)不会在h4标记中提取span标记。在

示例HTML是:

<div class="event-specifics">
 <div class="event-location">
  <h3>   Gourmet Matinee </h3>
  <h4>
   <span id="spanEventDetailPerformanceLocation">Knight Grove</span>
  </h4>
</div>
</div>

我试图在span标记中抓取文本“Knight Grove”。在命令行上使用scrapy shell时

^{pr2}$

退货:

['Knight Grove']

以及

response.xpath('.//div[@class="event-location"]/node()')

返回整个节点,即:

['\n                    ', '<h3>\n                        Gourmet Matinee</h3>', '\n                    ', '<h4><span id="spanEventDetailPerformanceLocation"><p>Knight Grove</p></span></h4>', '\n                ']

但是,当相同的Xpath在spider中运行时,不会返回任何内容。以下面的spider代码为例,这些代码是为获取上面的示例HTML而编写的,https://www.clevelandorchestra.com/17-blossom--summer/1718-gourmet-matinees/2017-07-11-gourmet-matinee/。(部分代码被删除,因为它与问题无关):

# -*- coding: utf-8 -*-
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.loader import ItemLoader
from concertscraper.items import Concert
from scrapy.contrib.loader import XPathItemLoader
from scrapy import Selector
from scrapy.http import XmlResponse

class ClevelandOrchestra(CrawlSpider):
    name = 'clev2'
    allowed_domains = ['clevelandorchestra.com']

    start_urls = ['https://www.clevelandorchestra.com/']

    rules = (
         Rule(LinkExtractor(allow=''), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
     thisconcert = ItemLoader(item=Concert(), response=response)
     for concert in response.xpath('.//div[@class="event-wrap"]'): 

        thisconcert.add_xpath('location','.//div[@class="event-location"]//span//text()')

     return thisconcert.load_item()

这不返回任何项['location']。我也试过:

thisconcert.add_xpath('location','.//div[@class="event-location"]/node()')

与上面关于p within h的问题中的不同,除非我弄错了,否则在HTML的h标记中允许使用span标记?在

为了清楚起见,“location”字段是在Concert()对象中定义的,为了排除故障,我禁用了所有管道。在

h4中的span是否可能在某种程度上是无效的HTML;如果不是,是什么导致的?

有趣的是,使用add\u css()执行相同的任务,如下所示:

thisconcert.add_css('location','.event-location')

生成一个包含span标记但缺少内部文本的节点:

['<div class="event-location">\r\n'
          '                    <h3>\r\n'
          '                        BLOSSOM MUSIC FESTIVAL </h3>\r\n'
          '                    <h4><span '
          'id="spanEventDetailPerformanceLocation"></span></h4>\r\n'
          '                </div>']

为了确认这不是重复的:在这个特定的例子中,在h4标记内的span标记中有一个p标记;但是,当不涉及p标记时,也会发生相同的行为,例如at:https://www.clevelandorchestra.com/1718-concerts-pdps/1718-rental-concerts/1718-rentals-other/2017-07-21-cooper-competition/?performanceNumber=16195。在


Tags: from标记importdiveventresponsehtmllocation
1条回答
网友
1楼 · 发布于 2024-10-02 10:34:19

此内容通过Ajax调用加载。为了获取数据,您需要发出类似的POST请求,不要忘了添加内容类型为headers = {'content-type': "application/json"}的头,并得到Json文件作为响应。enter image description here

import requests

url = "https://www.clevelandorchestra.com/Services/PerformanceService.asmx/GetToolTipPerformancesForCalendar"
payload = {"startDate": "2017-06-30T21:00:00.000Z", "endDate": "2017-12-31T21:00:00.000Z"}
headers = {'content-type': "application/json"}

json_response = requests.post(url, json=payload, headers=headers).json()
for performance in json_response['d']:
    print(performance["performanceName"], performance["dateString"])

# Star-Spangled Spectacular Friday, June 30, 2017
# Blossom: Tchaikovskys Spectacular 1812 Overture Saturday, July 1, 2017
# Blossom: Tchaikovskys Spectacular 1812 Overture Sunday, July 2, 2017
# Blossom: A Salute to America Monday, July 3, 2017
# Blossom: A Salute to America Tuesday, July 4, 2017

相关问题 更多 >

    热门问题