【问题标题】:How to select a child element in Selector如何在 Selector 中选择子元素
【发布时间】:2012-08-23 18:43:32
【问题描述】:

我正在使用 HTMLXPathSelector 来解析 HTML 内容。并且目标网站有一个随机的 HTML 标签。例如:它的格式可能是:

<div class="doctor_ans">
  <h3>Title</h3>
  <p style="text-align: justify;">
    <span style="font-size: 12px;">
      <span style="font-family: arial,helvetica,sans-serif;">
        <font color="#000000">I would like to get contain here.</font>
      </span>
    </span>
  </p>    
</div>

<div class="doctor_ans">
  <h3>Title</h3>
  <p style="text-align: justify;">
    <span style="font-size: 12px;">
      <span style="font-family: arial,helvetica,sans-serif;">
        I would like to get contain here.>
      </span>
    </span>
  </p>    
</div>

<div class="doctor_ans">
  <h3>Title</h3>
  <p>
    <span style="font-size: 12px;">
      <span style="font-family: arial,helvetica,sans-serif;">
        <font color="#000000">I would like to get contain here.</font>
      </span>
    </span>
  </p>    
</div>

<div class="doctor_ans">
  <h3>Title</h3>
  <p>
    <span style="font-size: 12px;">
        I would like to get contain here.
    </span>
  </p>    
</div>

等等。
请给我你的建议如何解析这个内容。 HTML 标记随机出现。所以,我需要一种方法来获取子元素以找到最终元素。

【问题讨论】:

  • 问题是?你试过什么?

标签: python beautifulsoup lxml scrapy


【解决方案1】:
hxs = HtmlXPathSelector(response)
hxs.select('div[@class="doctor_ans"]/p[1]//text()').extract()

将在doctor_ans div 的第一段中为您提供每个单独文本的列表。

【讨论】:

    【解决方案2】:

    我有更多使用 Selenium 的经验,但 xpath 部分应该是相同的。使用 xpath='.//span' 选择子元素,然后获取该元素的 .text。如果子元素为空,则丢弃,移动到下一个元素。

    【讨论】:

      猜你喜欢
      • 2020-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-15
      • 2019-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多