我有这样一段代码:如何遍历列表直至找到匹配项?
class MySpider(Spider):
name = 'smm'
allowed_domains = ['*']
start_urls = ['http://www.theguardian.com/media/social-media']
def parse(self, response):
items = []
#Define keywords present in metadata to scrap the webpage
keywords = ['social media','social business','social networking','social marketing','online marketing','social selling',
'social customer experience management','social cxm','social cem','social crm','google analytics','seo','sem',
'digital marketing','social media manager','community manager']
for link in response.xpath("//a"):
item = SocialMediaItem()
#Extract webpage keywords
metakeywords = link.xpath('//meta[@name="keywords"]').extract()
#Compare keywords and extract if one of the defined keyboards is present in the metadata
for metaKW in metakeywords:
if metaKW in keywords:
item['SourceTitle'] = link.xpath('/html/head/title').extract()
item['TargetTitle'] = link.xpath('text()').extract()
item['link'] = link.xpath('@href').extract()
outbound = str(link.xpath('@href').extract())
if 'http' in outbound:
items.append(item)
return items
它的目的是比较变量“关键字”(列表)与可变“的MetaKeywords”,这是使用link.xpath('//meta[@name="keywords"]').extract()
提取的网页的关键字。比较它时,如果找到单个匹配项,则应提取项目并在最后一条if语句中将它们追加为shownb。但是,它没有结果。我知道它应该抛出一些东西,因为我检查了网页的网址(http://www.socialmediaexaminer.com/)。 Chan有人帮忙吗? 干杯!
Dani
这是目前不可能回答你的问题有两个主要原因:(1)由于“for”循环的结构,“关键字”变量一次一个地接受“元关键字”中每个项目的值;因此你的“if”陈述是微不足道的,因为它总是会评估为真。如果“元关键字”是列表的列表/集合,并且您没有显示或具体告诉我们“元关键字”是什么类型的对象,则“关键字”只是一个列表。 (2)阅读这段代码的人不知道“item”对象是什么,也不知道“items”列表是如何或何时被初始化的。 – 2014-12-03 18:00:20
感谢您的意见洋红色新星。我更新了代码。 – 2014-12-03 18:13:43
感谢您的更新,但请仔细阅读我的第一点。如果你还没有,我想你需要阅读for循环的python文档。 – 2014-12-03 18:28:14