[英]Python/Django Save scraped data automatically to my database
我想将抓取的链接保存到数据库中,以便在以后运行时,它仅抓取并将新链接附加到列表中。
这是我下面的代码,但最终我的数据库为空。 我可以做些什么改变来克服这个问题? 提前致谢
from django.template.loader import get_template
from django.shortcuts import render_to_response
from bs4 import BeautifulSoup
import urllib2, sys
import urlparse
import re
from listing.models import jobLinks
#this function extract the links
def businessghana():
site = "http://www.businessghana.com/portal/jobs"
hdr = {'User-Agent' : 'Mozilla/5.0'}
req = urllib2.Request(site, headers=hdr)
jobpass = urllib2.urlopen(req)
soup = BeautifulSoup(jobpass)
for tag in soup.find_all('a', href = True):
tag['href'] = urlparse.urljoin('http://www.businessghana.com/portal/', tag['href'])
return map(str, soup.find_all('a', href = re.compile('.getJobInfo')))
# result from businssghana() saved to a variable to make them iterable as a list
all_links = businessghana()
#this function should be saving the links to the database unless the link already exist
def save_new_links(all_links):
current_links = jobLinks.objects.all()
for i in all_links:
if i not in current_links:
jobLinks.objects.create(url=i)
# I called the above function here hoping that it will save to database
save_new_links(all_links)
# return my httpResponse with this function
def display_links(request):
name = all_links()
return render_to_response('jobs.html', {'name' : name})
我的django models.py看起来像这样:
from django.db import models
class jobLinks(models.Model):
links = models.URLField()
pub_date = models.DateTimeField('date retrieved')
def __unicode__(self):
return self.links
您的代码有一些问题。 首先, jobLinks
模型没有url
字段。 您应该在create()
语句中使用links=i
。 其次,您要检查字符串url是否在QuerySet中。 永远不会这样,因为QuerySet的元素是模型类的对象,在您的情况下是jobLinks
对象。 相反,您可以执行以下操作:
def save_new_links(all_links):
new_links = []
for i in all_links:
if not jobLinks.objects.filter(links=i):
new_links.append(jobLinks(links=i))
jobLinks.objects.bulk_create(new_links)
我还建议将来在模型中使用单数形式的单词。 例如,在这种情况下,我将模型jobLink
和field link
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.