将数据保存在Postgresql数据库中

时间:2019-07-10 08:21:31

标签: python django postgresql web-scraping

我不了解如何将抓取的数据保存在Postgresql数据库中。 我试图使用Psycopg2没有效果... 我了解到可以为此使用django模型

抓取工具应抓取每个页面上的每个博客文章,抓取工具中的数据应进入Postgresql数据库,该数据库将计算以下统计信息:

1。地址/ stats下的10个最常见的单词及其数字

2。地址/统计信息/ /

下提供了每位作者的10个最常用词
  1. 在地址/统计///地址/作者/下提供作者的帖子

例如,在下面的代码中,我尝试获取作者的姓名,但出现这样的错误:

authors = Author(name='author name')
TypeError: 'NoneType' object is not callable

将模型导入刮板也无济于事...

这是我的刮刀:

import requests
from bs4 import BeautifulSoup as bs
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from collections import Counter


url = 'https://teonite.com/blog/page/{}/index.html'
all_links = []


headers = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'User-Agent': 'Mozilla/5.0'
}
with requests.Session() as s:
    r = s.get('https://teonite.com/blog/')
    soup = bs(r.content, 'lxml')
    article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')]
    all_links.append(article_links)
    num_pages = int(soup.select_one('.page-number').text.split('/')[1])


    for page in range(2, num_pages + 1):
        r = s.get(url.format(page))
        soup = bs(r.content, 'lxml')
        article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')]
        all_links.append(article_links)



    all_links = [item for i in all_links for item in i]

    d = webdriver.Chrome(ChromeDriverManager().install())

    contents = []
    authors = []

    for article in all_links:
        d.get(article)
        soup = bs(d.page_source, 'lxml')
        [t.extract() for t in soup(['style', 'script', '[document]', 'head', 'title'])]
        visible_text = soup.getText()
        content = soup.find('section', attrs={'class': 'post-content'})
        contents.append(content)
        Author = soup.find('span', attrs={'class': 'author-content'})
        authors.append(Author)

##  Below is the two lines of code where is the error

        authors = Author(name='author name')
        Author.save()

        unique_authors = list(set(authors))
        unique_contents = list(set(contents))
        try:
            print(soup.select_one('.post-title').text)
        except:
            print(article)
            print(soup.select_one('h1').text)
            break  # for debugging
    d.quit()

型号:

from django.db import models

class Author(models.Model):
    author_id = models.CharField(primary_key=True, max_length=50, editable=False)
    author_name = models.CharField(max_length=50)

    class Meta:
        ordering = ['-author_id']
        db_table = 'author'


class Stats(models.Model):
    content = models.CharField(max_length=50)
    stats = models.IntegerField()

    class Meta:
        ordering = ['-stats']
        db_table = 'stats'



class AuthorStats(models.Model):
    author_id = models.CharField(max_length=100)
    content = models.CharField(max_length=100)
    stats = models.IntegerField()

    class Meta:
        ordering = ['stats']
        db_table = 'author_stats'

2 个答案:

答案 0 :(得分:0)

您已将Author设置为模型以外的其他值:

Author = soup.find('span', attrs={'class': 'author-content'})

导入模型Author,不要隐藏它。

(您正在使用authors做类似的事情。)

答案 1 :(得分:0)

您以错误的方式使用Author。您需要:

  1. 导入您的模型。py
  2. 您不需要本地authors列表。
  3. Author = soup.find('span', attrs={'class': 'author-content'})更改为author_raw = soup.find('span', attrs={'class': 'author-content'})
  4. 通过author = models.Author(name=author_raw.name)创建作者,并通过author.save()保存。 (我不知道soap.find为作者带来了什么,因此您可以在Author模型构造函数参数中编辑该部分。)