簡體   English   中英

python scrapy如何刪除多余的解析字符

[英]python scrapy how to remove extra parsed character

在使用scrapy的解析過程中,我找到了此輸出

[u'TARTARINI AUTO SPA(CENTRALINO SELEZIONE PASSANTE)'],“ [u'VCBONAZZI \\ xa043',u'40013',u'CASTEL MAGGIORE']”,[u'0516322411'],[u'info @ tartariniauto。 it'],[u'CARS(LPG INSTALLERS)'],[u'track.aspx?id = 0&url = http://www.tartariniauto.it']

如您所見,還有一些額外的字符,例如

u'\\ xa043“'[]

我不想的。 我如何刪除這些? 此外,該字符串中還有5個項目。 我希望字符串看起來像這樣:

item1,item2,item3,item4,item5

這是我的pipelines.py代碼

from scrapy.contrib.loader import ItemLoader
from scrapy.contrib.loader.processor import TakeFirst, MapCompose, Join
import re
import json
import csv

class InfobelPipeline(object):
    def __init__(self):
      self.file = csv.writer(open('items.csv','wb'))
    def process_item(self, item, spider):
      name = item['name']
      address = item['address']
      phone = item['phone']
      email = item['email']
      category = item['category']
      website = item['website']
      self.file.writerow((name,address,phone,email,category,website))
    return item

謝謝

您看到的多余字符是unicode字符串。 如果您在網絡上抓取,就會看到很多東西。 常見示例包括版權符號:©unicode點U+00A9或商標符號™unicode點U+2122

刪除它們的最快方法是嘗試將它們編碼為ascii,如果它們不是ascii字符(它們都不是),則將其丟棄

>>> example = u"Xerox ™ printer"
>>> example
u'Xerox \u2122 printer'
>>> example.encode('ascii')
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2122' in position 6: ordinal 
not in range(128)
>>> example.encode('ascii', errors='ignore')
'Xerox  printer'
>>>

如您所見,當您嘗試將符號解碼為ascii時,會引發UnicodeEncodeError因為該字符無法以ascii表示。 但是,如果您添加errors='ignore'關鍵字參數,則它將僅忽略無法編碼的符號。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM