【发布时间】:2018-06-28 16:38:32
【问题描述】:
我正在尝试使用 Scrapy 从包含内联图标和其他标签的 p 中提取和清理一些文本。特别是,我想用从图像src属性中提取的文本替换图像标签:
from scrapy.selector import Selector
text = '''
<p id="1"><b><br></b>For service <i>to </i>these stations, take the <img src="images/1.png"> to 72 St or Times Sq-42 St and transfer
<br>to an uptown <img src="images/1.png"> or <img src="images/2.png"> <i>local</i>.
<br>
<br>For service <i>from </i>these stations, take the <img src="images/1.png"> or <img src="images/2.png"> to 72 St or 96 St and transfer
<br>to a South Ferry-bound <img src="images/1.png">.
<br><b>______________________________<br></b>
</p>
'''
sel = Selector(text=text)
# do stuff
我要找的结果是字符串:
如需前往这些车站,请乘坐 (1) 到 72 St 或 Times Sq-42 St,然后转乘到住宅区 (1) 或 (2) 当地。从这些车站乘坐 (1) 或 (2) 到 72 St 或 96 St,然后换乘前往南码头的 (1)。
我可以使用以下方法从src 中提取文本:
node.css('img').xpath('@src').re_first(r'images/(.+).png')
但我坚持如何遍历子节点并确定它是否是文本节点/如何过滤掉其他内联标签。这是我所在的位置:
description = sel.css('p#1')
def clean_html(description):
for n in description.xpath('node()'):
if (n.xpath('self::img')):
yield n.xpath('@src').re_first(r'images/(.+).png')
if (n.xpath('self::text()')):
yield n.css('::text')
text = ''.join(clean_html(description))
【问题讨论】: