![](/img/trans.png)
[英]How do i best store web crawled data collected daily to look for changes
[英]How do I store crawled data into a database
我對python以及這個問題中我將要談論的所有其他事物還很陌生,但是我想開始一個我已經考慮了一段時間的項目。 基本上,我想對Web進行爬網,並在對URL進行實時爬網時以及在網頁上實時顯示它們。 我編寫了一個簡單的搜尋器,將網址存儲在列表中。 我想知道如何將此列表添加到數據庫中,並每隔x秒更新一次數據庫,以便可以訪問該數據庫並定期在網頁上輸出鏈接列表。
我對實時Web開發了解不多,但這是另一天的話題。 但是,現在,我更關心如何將列表放入數據庫。 我目前正在使用非常容易相處的web2py框架,但是如果你們對我應該看的地方,應該檢查哪些框架有任何建議,請在回答中也發表評論,謝謝。
簡而言之,我不擅長於:Python,數據庫,實時Web開發。
這是我的搜尋器的代碼,如果仍然有幫助的話:)謝謝
from urllib2 import urlopen
def crawler(url,x):
crawled=[]
tocrawl=[]
def crawl(url,x):
x=x+1
try:
page = urlopen(url).read()
findlink = page.find('<a href=')
if findlink == -1:
return None, 0
while findlink!=-1:
start = page.find(('"'), findlink)
end = page.find(('"'), start+1)
link = page[start+1:end]
if link:
if link!=url:
if link[0]=='/':
link=url+link
link=replace(link)
if (link not in tocrawl) and (link!="") and (link not in crawled):
tocrawl.append(link)
findlink = page.find('<a href=', end)
crawled.append(url)
while tocrawl:
crawl(tocrawl[x],x)
except:
#keep crawling
crawl(tocrawl[x],x)
crawl(url,x)
def replace(link):
tsp=link.find('//')
if tsp==-1:
return link
link=link[0:tsp]+'/'+link[tsp+2:]
return link
而不是將URL放入列表中,為什么不將它們直接寫入db? 使用例如mysql:
import MySQLdb
conn = MySQLdb.connect('server','user','pass','db')
curs = conn.cursor()
sql = 'INSERT into your_table VALUES(%s,%s)' %(id,str(link))
rc = curs.execute(sql)
conn.close()
這樣,您就不必像管道一樣管理列表。 但是,如果有必要,也可以對該方法進行調整。
對於具有內置列表結構的Redis來說 ,這聽起來不錯。 要將新的url附加到列表中,方法很簡單:
from redis import Redis
red = Red()
# Later in your code...
red.lpush('crawler:tocrawl', link)
它還具有一種設置類型,可讓您有效地檢查已爬網的網站並同步多個爬網程序。
# Check if we're the first one to mark this link
if red.sadd('crawler:crawled', link):
red.lpush('crawler:tocrawl', link)
要獲取下一個要抓取的鏈接:
url = red.lpop('crawler:tocrawl')
要查看哪些網址正在排隊進行爬網,請執行以下操作:
print red.lrange('crawler:tocrawl', 0, -1)
它只是一種選擇,但是它非常快速且靈活。 您可以在redis python驅動程序頁面上找到更多文檔。
為此,您需要Cron。 cron是用於類Unix計算機的作業調度程序。 您可以安排一份定時工作,每分鍾,每小時,每天等等。
請查看本教程http://newcoder.io/scrape/intro/ ,它將幫助您在此處實現所需的目標。
謝謝。 信息,如果它工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.