我正在研究大数据的网络抓取,所以我编写了以下代码来从我们校园的本地服务器获取一些信息。它工作正常,但我认为性能很慢;每条记录需要 0.91 秒才能存储到数据库中。代码所做的是打开一个网页,获取一些内容并将其存储在磁盘上。
我的目标是将抓取记录所用的时间降低到接近 0.4 秒(或更少,如果可能的话)。
#!/usr/bin/env python
import scraperwiki
import requests
import lxml.html
for i in range(1, 150):
try:
html = requests.get("http://testserver.dc/"+str(i)"/").content
dom = lxml.html.fromstring(html)
for entry in dom.cssselect('.rTopHeader'):
name = entry.cssselect('.bold')[0].text_content()
for entry in dom.cssselect('div#rProfile'):
city = entry.cssselect('li:nth-child(2) span')[0].text_content()
for entry in dom.cssselect('div#rProfile'):
profile_id = entry.cssselect('li:nth-child(3) strong a')[0].get('href')
profile = {
'name':name,
'city':city,
'profile_id':profile_id
}
unique_keys = [ 'profile_id' ]
scraperwiki.sql.save(unique_keys, profile)
print jeeran_id
except:
print 'Error: ' + str(i)