0
下面是一段我想用Scrapy刮掉的HTML代碼片段。從Scrapy輸出中刪除文本
<body>
<h2 class="post-title entry-title">Sample Header</h2>
<div class="entry clearfix">
<div class="sample1">
<p>Hello</p>
</div>
<!--start comment-->
<div class="sample2">
<p>World</p>
</div>
<!--end comment-->
</div>
<ul class="post-categories">
<li><a href="123.html">Category1</a></li>
<li><a href="456.html">Category2</a></li>
<li><a href="789.html">Category3</a></li>
</ul>
</body>
現在我使用下面的工作scrapy代碼:
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from isbullshit.items import IsBullshitItem
class IsBullshitSpider(CrawlSpider):
name = 'isbullshit'
start_urls = ['http://sample.com']
rules = [Rule(SgmlLinkExtractor(allow=[r'page/\d+']), follow=True),
Rule(SgmlLinkExtractor(allow=[r'\w+']), callback='parse_blogpost')]
def parse_blogpost(self, response):
hxs = HtmlXPathSelector(response)
item = IsBullshitItem()
item['title'] = hxs.select('//h2[@class="post-title entry-title"]/text()').extract()[0]
item['tag'] = hxs.select('//ul[@class="post-categories"]/li[1]/a/text()').extract()[0]
item['article_html'] = hxs.select("//div[@class='entry clearfix']").extract()[0]
return item
它給了我下面的XML輸出:
<?xml version="1.0" encoding="utf-8"?>
<items>
<item>
<article_html>
<div class="entry clearfix">
<div class="sample1">
<p>Hello</p>
</div>
<!--start comment-->
<div class="sample2">
<p>World</p>
</div>
<!--end comment-->
</div>
</article_html>
<tag>
Category1
</tag>
<title>
Sample Header
</title>
</item>
</items>
我想知道如何實現以下輸出:
<?xml version="1.0" encoding="utf-8"?>
<items>
<item>
<article_html>
<div class="entry clearfix">
<div class="sample1">
<p>Hello</p>
</div>
<!--start comment-->
<!--end comment-->
</div>
</article_html>
<tag>
Category1,Category2,Category3
</tag>
<title>
Sample Header
</title>
</item>
</items>
注意:類別的數量取決於帖子。在上面的例子中,有三個類別。可能會有更多或更少。
幫助將不勝感激。乾杯。
我不知道如何操縱我的代碼,因爲我是一個新手。如果你能在我的問題中根據場景給我寫一段代碼,那將是非常好的。 – vrtech77