下面是爬取携程景点数据的代码,为什么输出不了,有什么解决方法,急!
当然我这篇文章主要的目的是记录我今天学习了字典的items()函数
网上对items()给出的描述是:
Python 字典 items() 方法以列表返回可遍历的(键, 值) 元组数组。
使用方法:
①不需要给其任何参数
②返回值:以列表形式返回可遍历的(键, 值) 元组数组。dict.item()
我们在python当中测试一下:
dic = {'apple': '1','orange':'2','banana':'3'}
print(dic.items())
输出结果为
dict_items([('apple', '1'), ('orange', '2'), ('banana', '3')])
嗯哼,返回了一个列表果然,那么我们自然就可以用一个for循环得到其键值
for i in dic.items():
print(i)
# 输出结果为:
('apple', '1')
('orange', '2')
('banana', '3')
但是,我们如果我们像单独得到其键与值呢?
因此我们先看看上面这个代码每次输出的结果到底是什么类型type(i)
最后得到结果<class 'tuple'>
,果然和我们想的一样是个元组,那么我们便可以像这样得到其键值咯!
dic = {'apple': '1', 'orange': '2', 'banana': '3'}
print(dic.items())
for i, j in dic.items():
print(i, ':', j)
完成!!!又学到新东西了,yeah!!!继续加油!!!
可能的解决方案: 1. 检查代码中是否正确使用了yield语句输出item,如果使用return则无法输出。需要将代码中的return改为yield。 2. 检查是否正确导入了相关的模块,如scrapy等。 3. 检查是否设置了正确的爬虫名字和允许的域名。 4. 检查是否正确定义了item,包括名称和属性。 5. 检查是否在代码中正确使用了item,并将数据存入其中。 6. 如果以上方案都不行,可以试着增加日志记录代码,查看程序运行时出现的报错信息,并进行调试。
代码示例: 参考以下示例,假设要爬取的字段为name和location,存入的item为SceneryItem:
from scrapy import Spider from scrapy.selector import Selector from project.items import SceneryItem
class ScenerySpider(Spider): name = 'scenery' allowed_domains = ['ctrip.com']
def start_requests(self):
urls = [
'https://you.ctrip.com/sight Beijing 1.html'
]
for url in urls:
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, response):
sel = Selector(response)
items = []
scenerys = sel.xpath('//div[@class="list_mod2"]')
for scenery in scenerys:
item = SceneryItem()
item['name'] = scenery.xpath('name/text()').extract_first().strip()
item['location'] = scenery.xpath('location/text()').extract_first().strip()
items.append(item)
yield item
self.logger.info('Parsed %s items' % len(items))
在代码中,定义了爬虫名字为scenery,允许的域名为ctrip.com,通过yield语句将爬取到的数据存入item,并输出。同时使用日志记录代码,方便调试和查错。
抓包调试下, 携程现在不断在增加反爬虫的措施。