【发布时间】:2016-04-04 02:25:26
【问题描述】:
我正在尝试使用 Scrapy 从该站点进行抓取:http://www.fs.fed.us/research/people/profile.php?alias=ggonzalez
这是返回我在蜘蛛中导出的最终项目的函数:
def parse_post(self, response):
theitems = []
pubs = response.xpath("//div[@id='pubs']/ul/li/a")
for i in pubs:
item = FspeopleItem()
name = str(response.xpath("//div[@id='maincol']/h1/text() | //nobr/text()").extract()).strip()
pub = str(i.xpath("@title").extract()).strip()
item['link'] = response.url
item['name'] = name
item['pub'] = pub
theitems.append(item)
return theitems
由于某种原因,返回的“theitems”总是将重音字符(如 Díaz 中的 í)显示为空格。我不知道为什么会这样。当我打开一个 Scrapy shell 并与 xpath 分开打印信息时,它可以很好地打印到控制台,但是当它从返回的“theitems”中出来时,它变成了一个空白区域。我已经在 Python2.7 和 3.5 中测试过它。
我是 Scrapy 的新手,一般是编码,一般是 python。但是,除了这个编码问题之外,一切正常。有谁知道为什么会这样?
谢谢。
//////编辑////////
感谢您的建议。虽然格式更好,因为当我使用以下代码时 /u' 东西消失了(通过使用
.encode("utf-8")
和
.extract_first()
在撰写我的项目时),带有口音的字符仍然很时髦。因此,我查看了我正在抓取的网站上的编码,发现它们使用的是 ISO-8859-1 编码。所以我尝试了
.encode("ISO-8859-1")
向项目添加组件时,当我打开 .csv 时,这正确显示了带有重音符号等的字符(所有格式都很棒)。然而,当我这样做时,大约 25% 的网站没有被抓取——csv 有 ~1400 个条目而不是 ~2100 个。我不明白为什么它不抓取某些网站而不抓取其他网站?
import scrapy
from fspeople.items import FspeopleItem
class FSSpider(scrapy.Spider):
name = "hola"
allowed_domains = ["fs.fed.us"]
start_urls = [
"http://www.fs.fed.us/research/people/people_search_results.php?employeename=&keywords=&station_id=SRS&state_id=ALL"]
def __init__(self):
self.i = 0
def parse(self,response):
for sel in response.xpath("//a[@title='Click to view their profile ...']/@href"):
url = response.urljoin(sel.extract())
yield scrapy.Request(url, callback=self.parse_post)
self.i += 1
def parse_post(self, response):
theitems = []
pubs = response.xpath("//div[@id='pubs']/ul/li")
for i in pubs:
item = FspeopleItem()
name = response.xpath("//div[@id='maincol']/h1/text() | //nobr/text()").extract_first().strip().encode("ISO-8859-1")
pubname = i.xpath("a/text()").extract_first().strip().encode("ISO-8859-1")
pubauth = i.xpath("text()").extract_first().strip().encode("ISO-8859-1")
item['link'] = response.url
item['name'] = name
item['pubname'] = pubname
item['pubauth'] = pubauth
theitems.append(item)
return theitems
【问题讨论】:
-
当你说“总是显示重音字符”时,你用什么软件来显示输出,你用什么输出格式?