我对python还不熟悉,正在玩弄这个蹩脚的网络爬虫。 我想抓取描述字符串的前10个字符并将其用作标题
下面的python代码片段生成了下面的JSON
item['image'] = img.xpath('@src').extract()
item_desc = img.xpath('@title').extract()
print(item_desc)
item['description'] = item_desc
item['title'] = item_desc[:10]
item['parentUrl'] = response.url
{'description': [u'CHAR-BROIL Tru-Infrared 350 IR Gas Grill - SportsAuthority.com '],
'image': [u'http://www.sportsauthority.com/graphics/product_images/pTSA-10854895t130.jpg'],
'parentUrl': 'http://www.sportsauthority.com/category/index.jsp?categoryId=3077576&clickid=topnav_Jerseys+%26+Fan+Shop',
'title': [u'CHAR-BROIL Tru-Infrared 350 IR Gas Grill - SportsAuthority.com ']}
我想要的是下面的。切片的行为不符合我的预期。你知道吗
{'description': [u'CHAR-BROIL Tru-Infrared 350 IR Gas Grill - SportsAuthority.com '],
'image': [u'http://www.sportsauthority.com/graphics/product_images/pTSA-10854895t130.jpg'],
'parentUrl': 'http://www.sportsauthority.com/category/index.jsp?categoryId=3077576&clickid=topnav_Jerseys+%26+Fan+Shop',
'title': [u'CHAR-BROIL']}
item_desc
是一个列表,其中有一个元素,该元素是一个unicode字符串。它本身不是unicode字符串。[...]
是一个很大的暗示。你知道吗取出元素,切片,然后将其放回列表中:
显然,
.extract()
函数可以返回多个匹配项;如果只需要一个匹配项,也可以选择第一个:如果XPath查询并不总是返回结果,请首先测试空列表:
相关问题 更多 >
编程相关推荐