繁体   English   中英

如果其他HTML位于标记中,如何从div标记中提取python中的文本?

[英]How to extract text in python from div tag if other html is within the tag?

我正在尝试提取参考。 HTML中的scrapy的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。 我第一次尝试使用xpath时,某些爬网项目没有<p>标记,也没有<span>

尝试从最后一个表达式中删除::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]+)')

您无需使用remove_tags因为您可以使用选择器直接获取text

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM