【发布时间】:2017-10-12 14:14:37
【问题描述】:
您好我想从http://economictimes.indiatimes.com/archive.cms抓取数据,所有的url都是根据日期、月份和年份归档的,首先获取url列表我使用的是https://github.com/FraPochetti/StocksProject/blob/master/financeCrawler/financeCrawler/spiders/urlGenerator.py的代码,修改了我网站的代码作为,
import scrapy
import urllib
def etUrl():
totalWeeks = []
totalPosts = []
url = 'http://economictimes.indiatimes.com/archive.cms'
data = urllib.urlopen(url).read()
hxs = scrapy.Selector(text=data)
months = hxs.xpath('//ul/li/a').re('http://economictimes.indiatimes.com/archive.cms/\\d+-\\d+/news.cms')
admittMonths = 12*(2013-2007) + 8
months = months[:admittMonths]
for month in months:
data = urllib.urlopen(month).read()
hxs = scrapy.Selector(text=data)
weeks = hxs.xpath('//ul[@class="weeks"]/li/a').re('http://economictimes.indiatimes.com/archive.cms/\\d+-\\d+/news/day\\d+\.cms')
totalWeeks += weeks
for week in totalWeeks:
data = urllib.urlopen(week).read()
hxs = scrapy.Selector(text=data)
posts = hxs.xpath('//ul[@class="archive"]/li/h1/a/@href').extract()
totalPosts += posts
with open("eturls.txt", "a") as myfile:
for post in totalPosts:
post = post + '\n'
myfile.write(post)
etUrl()
将文件保存为urlGenerator.py 并使用命令$ python urlGenerator.py 运行
我没有得到任何结果,有人可以帮助我如何将此代码用于我的网站用例或任何其他解决方案?
【问题讨论】:
-
是否存在
etUrl()的调用,传统上由if __name__ == "__main__": etUrl()类型结构保护? -
安装 Scrapy 然后使用基于
urllib的请求响应也是 非常奇怪;可以说,Scrapy 50% 的能力在于它如何处理整个过程——包括定义明确的回调来避免你在那里进行的 4 深缩进 -
我冒昧地清理了您的帖子,因为我假设您并不是要在底部递归调用
etUrl()... -
但是,查看您修改的代码,看起来
for循环没有按照您显示的方式嵌套。您发布的代码实际上是您的真实代码吗?在 Python 中,缩进很重要很多,所以请确保您发布的内容符合您实际运行的代码。