python 如何将抓取的数据存储到数据库中

mutmk8jj  于 11个月前  发布在  Python
关注(0)|答案(3)|浏览(72)

我正在尝试做一个网络爬虫。我有这样一段代码,它可以实时抓取一个页面,并将一些URL存储在一个列表中,使用web2py框架:

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

字符串
如何将此列表存储到数据库中并定期更新,以便定期访问数据库并输出网页上的链接列表?

oiopk7p5

oiopk7p51#

与其将URL放入列表中,为什么不直接将它们写入数据库?例如使用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()

字符串
这样你就不必像管道一样管理列表了。但是如果有必要的话,也可以为该方法进行调整。

bqf10yzr

bqf10yzr2#

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')


要查看哪些URL已排队等待爬网:

print red.lrange('crawler:tocrawl', 0, -1)


这只是一个选项,但它非常快速和灵活。你可以在redis python driver页面找到更多的文档。

toiithl6

toiithl63#

要实现这一点,你需要一个Cron。Cron是一个用于类Unix计算机的作业调度器。你可以安排一个Cron作业每分钟、每小时、每天等进行。
看看这个教程http://newcoder.io/scrape/intro/,它将帮助你实现你想要的。
多谢。如果有用的话。

相关问题