我使用scrapy从几个亚洲网站上抓取一些东西。其中一些使用 utf8 编码。但其他一些使用不同的,如“gb2312”。
我编写自己的输出语句而不是管道和项目。这是yelp餐厅评论的scrapy代码,它有效:
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
#from crawlsite.items import ReviewItem
import re
class ReviewSpider(BaseSpider):
name = "yelp"
allowed_domains = ['yelp.com']
start_urls = ['http://www.yelp.com/biz/providence-los-angeles-2']
#call back function when received response
def parse(self, response):
hxs = HtmlXPathSelector(response)
stars = hxs.select('//meta[@itemprop="ratingValue"]/@content').extract()
review = hxs.select('//p[@itemprop="description"]').extract()
url = response.url
date = hxs.select('//meta[@itemprop="datePublished"]/@content').extract()
user = hxs.select('//li[@class="user-name"]/a/text()').extract()
file = open('crawled.xml', 'a')
starting = str(url)[55:]
startingid = 0
if starting.isdigit():
startingid = int(starting)
id = 0
while id < 40:
file.write('\n<doc id="%s">\n' % str(id + 1 + startingid))
#the first stars rating is the overall rating
file.write('\t<stars>%s</stars>\n' % stars[id+1])
file.write('\t<url>\n\t%s\n\t</url>\n' % url)
file.write('\t<date>%s</date>\n' % date[id])
#user can be unicode as well
file.write('\t<user>%s</user>\n' % user[id].encode('utf8'))
#there is no title for yelp reviews
file.write('\t<title>NULL</title>\n')
#need to stripe the review
file.write('\t<review>\n\t')
review[id] = re.sub('<[^<]+?>', '', review[id])
file.write(review[id].encode('utf8'))
file.write('\n\t</review>\n')
star = stars[id+1]
polarity = "NULL"
confidence = "NULL"
file.write('\t<polarity>%s</polarity>\n' % polarity)
file.write('\t<confidence>%s</confidence>\n' % confidence)
file.write('</doc>\n')
id += 1
file.close()
请注意,有些评论包含法语或西班牙语单词,但它们都在 'utf8' 中,
file.write(review[id].encode('utf8'))
这是使用不同编码抓取亚洲网站的代码:
allowed_domains = ['duanwenxue.com']
start_urls = ['http://www.duanwenxue.com/article/113415.html']
def parse(self, response):
hxs = HtmlXPathSelector(response)
content = hxs.select('//div[@class="content-in-similar"]/p/text()').extract();
file = open('crawled.xml', 'a')
file.write(str(content).decode('GB2312'))
file.close()
输出文件是这样的:
[u'\u4e00\u5927\u5b66\u751f\u88ab\u654c\u4eba\u6293\u4e86\uff0c\u654c\u4eba\u628a\u4ed6\u7ed1\u5728\u4e86\u7535\u7ebf\u6746\u4e0a\uff0c\u7136\u540e\u95ee\u4ed6\uff1a\u8bf4\uff0c\u4f60\u662f\u54ea\u91cc\u7684\uff1f\u4e0d\u8bf4\u5c31\u7535\u6b7b\u4f60\uff01\u5927\u5b66\u751f\u56de\u4e86\u654c\u4eba\u4e00\u53e5\u8bdd\uff0c\u7ed3\u679c\u
我使用w3c检查编码,应该是正确的。我试过 str(content).decode('GB2312').encode('utf8') 和类似的组合,它们都不起作用。