我尝试使用Scrapy来设置一个简单的spider来定期检查a webpage以获取已发布文章的简单数据(标题和摘要url)。在
我将蜘蛛设置如下:
class JournalSpider(Spider):
name = "journal"
allowed_domains = ["ametsoc.org"]
start_urls = [
"http://journals.ametsoc.org/toc/wefo/current/"
]
def parse(self, response):
journalTitle = Selector(response).xpath('//*[@id="journalBlurbPanel"]/div[2]/h3/text()').extract()[0]
journalIssue = Selector(response).xpath('//*[@id="articleToolsHeading"]/text()').extract()[0].strip() # remove whitespace at start and end
# find all articles for the issue and parse each one individually
articles = Selector(response).xpath('//div[@id="rightColumn"]//table[@class="articleEntry"]')
for article in articles:
item = ArticleItem()
item['journalTitle'] = journalTitle
item['journalIssue'] = journalIssue
item['title'] = article.xpath('//div[@class="art_title"]/text()').extract()[0]
item['url'] = article.xpath('//a/@href').extract()[0]
yield item
它成功地提取了journalTitle
和{title
(第一篇文章的标题)。此外,我不知道url
是从哪里提取的,因为它与我在页面上看到的任何内容都没有关联:/action/ssostart?idp=https%3A%2F%2Fshib.ametsoc.org%2Fshibboleth%2Fidp
我觉得我一定是弄乱了xpath字符串(我是新来摆弄xpath的,如果是这样的话,我也不会感到惊讶!),或者当我通过Scrapy访问时,我可能得到了一个不同版本的站点?在
有什么想法吗?在
循环中的XPath表达式必须是上下文特定的,并以点开头:
也可以使用
extract_first()
方法代替extract()[0]
,并使用response.xpath()
快捷方式代替Selector(response).xpath()
。在相关问题 更多 >
编程相关推荐