如果标签中包含其他html,如何从div标签中提取python中的文本?

时间:2018-12-22 13:56:52

标签: python scrapy

我正在尝试提取裁判。 HTML中带有刮痕的ID:

<div class="col" itemprop="description">
  <p>text Ref.&nbsp;<span>220.20.34.20.53.001</span></p>
  <p>more text</p>
</div>

span和p标签并不总是存在。

使用xpath选择器:

text = ' '.join(response.xpath('//div[@itemprop="description"]/p/text()').extract()).replace(u'\xa0', u' ')
try: 
     ref_id = re.findall(r"Ref\.? ?((?:[A-Z\d\.]+)|(?:[\d.]+))", text)[0].strip()

在这种情况下,仅返回一个空字符串,因为标记中包含HTML。

现在尝试使用CSS选择器提取文本以使用remove_tags:

>>> ''.join([remove_tags(w).strip()for w in response.css('div[itemprop="description"]::text').extract()]) 

由于我无法抓取该项目,因此返回空结果。

无论div中是否包含html <p>标记,如何提取ref_id。某些爬网项没有<p>标记,也没有<span>,在我第一次尝试使用xpath的地方。

2 个答案:

答案 0 :(得分:1)

尝试从您的上一个表达式中删除::text

''.join([remove_tags(w).strip() for w in response.css('div[itemprop=description]').extract()]) 

但是如果您只需要从html中提取220.20.34.20.53.001,为什么不使用response.css('div[itemprop=description] p span::text').extract()

甚至是response.css('div[itemprop=description]').re(r'([\.\d]+)')

答案 1 :(得分:1)

您不需要使用remove_tags,因为您可以通过选择器直接获取text

sel.css('div[itemprop=description] ::text')

这将使用divitemprop="description"标记中获取所有内部文本,随后您可以使用正则表达式提取信息:

sel.css('div[itemprop=description] ::text').re_first('(?:\d+.)+\d+')
相关问题