我正在尝试抓取 http://www.dmoz.org/Computers/Programming/Languages/Python/Books此页面使用 scrapy 0.20.2。
我可以做我需要做的所有事情,比如获取信息和分类......
但是,我仍然在结果中得到\r 和\t 以及\n 。例如这是一个 json {"desc": ["\r\n\t\t\t\r\n ", "\r\n\t\t\t\r\n - 主要本书的目标是促进使用 Python 的面向对象设计并说明新兴的面向对象设计模式的使用。\r\n本书的第二个目标是及时提供数学工具。分析技术和证明是根据需要并在适当的上下文中呈现。\r\n\r\n "], "link": ["http://www.brpreiss.com/books/opus7/html/book.html"], "title ": ["Python 中具有面向对象设计模式的数据结构和算法"]},
数据是正确的,但我不想在结果中看到\t 和\r 和\n 。
我的蜘蛛是
from scrapy.spider import BaseSpider
from scrapy.selector import Selector
from dirbot.items import DmozItem
class DmozSpider(BaseSpider):
name = "dmoz"
allowed_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/Books/"
]
def parse(self, response):
sel = Selector(response)
sites = sel.xpath('//ul[@class="directory-url"]/li')
items = []
for site in sites:
item = DmozItem()
item['title'] = site.xpath('a/text()').extract()
item['link'] = site.xpath('a/@href').extract()
item['desc'] = site.xpath('text()').extract()
items.append(item)
return items
最佳答案
我用过:
def parse(self, response):
sel = Selector(response)
sites = sel.xpath('//ul/li')
items = []
for site in sites:
item = DmozItem()
item['title'] = map(unicode.strip,site.xpath('a/text()').extract())
item['link'] = map(unicode.strip, site.xpath('a/@href').extract())
item['desc'] = map(unicode.strip, site.xpath('text()').extract())
items.append(item)
print "hello"
return items
并且有效。我不确定它是什么,但我仍在阅读 unicode.strip。希望对您有所帮助
关于页面上的 Python 抓取仍然包含像\r\n\t 这样的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21091501/