【发布时间】:2015-09-17 02:07:47
【问题描述】:
我正在使用scrapy,我想提取文本元素。这是我要抓取的网页 http://www.idealo.de/preisvergleich/OffersOfProduct/3131289_-vitodens-222-f-13-kw-viessmann.html
我正在使用以下 xpath 命令:
for sel in response.xpath('//tr'):
sel.xpath('td[@class="title"]/a[@class="offer-title link-2 webtrekk wt-prompt"]/text()').extract()
html 代码中有产品(表中的行)可以正常工作。但是,在某些情况下,javascript 会直接嵌入到文本之前:
<td class="title">
<a class="offer-title link-2 webtrekk wt-prompt" ... >
<script type="text/javascript"> ... </script>
text I need
</a>
</td>
在这些情况下,我无法检索“我需要的文本”。
我还搜索并尝试了其他几个 xpath 选项,例如获取所有子节点。这些是我尝试过的变体:
# item['longtitle'] = sel.xpath('td[@class="title"]/a[@class="offer-title link-2 webtrekk wt-prompt"]/script[@type="text/javascript"]/following-sibling::*').extract()
# item['longtitle'] = sel.xpath('td[@class="title"]/a[@class="offer-title link-2 webtrekk wt-prompt"]/script[@type="text/javascript"]/node()').extract()
item['longtitle'] = sel.xpath('td[@class="title"]/text()[0]').extract()
## item['longtitle'] = sel.xpath('td[@class="title"]/node()').extract()
## item['longtitle'] = sel.xpath('td[@class="title"]/text()').extract()
## item['longtitle'] = sel.xpath('td[@class="title"]/a[@class="offer-title link-2 webtrekk wt-prompt"]/node()').extract()
## item['longtitle'] = sel.xpath('td[@class="title"]/a[@class="offer-title link-2 webtrekk wt-prompt"]/text()').extract()
## item['longtitle'] = sel.xpath('td[@class="title"]/a[2]').extract()
## item['longtitle'] = sel.xpath('td[@class="title"]/a[@class="offer-title link-2 webtrekk wt-prompt"]/*').extract()
## item['longtitle'] = sel.xpath('td[@class="title"]/a[@class="offer-title link-2 webtrekk wt-prompt"]/script[@type="text/javascript"]/text()').extract()
但我一直失败。
我很乐意提供任何帮助。谢谢。
【问题讨论】:
-
//td[@class="title"]/a[@class="offer-title link-2 webtrekk wt-prompt"]/text()[2]因为 -
感谢您的及时回复。我尝试了拆分文本的第二个元素,然后是第三个和第四个元素:[2]、[3] 和 [4]。它们都是空的。
标签: javascript python html xpath scrapy