【问题标题】:'WSGIRequest' object has no attribute 'Session' in django'WSGIRequest' 对象在 Django 中没有属性 'Session'
【发布时间】:2019-04-15 11:32:17
【问题描述】:

我正在尝试使用 Django 抓取一个新闻网站,这里的逻辑是用户只能在 24 小时时间跨度后才能抓取,我正在 youtube 上浏览这个教程。代码工作正常的地方可能是因为我不确定不同的 Django 版本。 但是当我尝试运行代码时,会出现类似这样的错误

'WSGIRequest' 对象没有属性'Session'

Internal Server Error: /scrape/
Traceback (most recent call last):
  File "C:\Users\adity\Desktop\django-scrapper\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\adity\Desktop\django-scrapper\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\adity\Desktop\django-scrapper\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\adity\Desktop\django-scrapper\src\news\views.py", line 20, in scrape
    session = requests.Session()
AttributeError: 'WSGIRequest' object has no attribute 'Session'

这是代码

from django.shortcuts import render, redirect

# Create your views here.
import requests
import os
import shutil

requests.packages.urllib3.disable_warnings()

from bs4 import BeautifulSoup
from datetime import timedelta, timezone, datetime
from .models import Headline, UserProfile

def scrape(requests):
    user_p = UserProfile.objects.filter(user=requests.user).first()
    if user_p is not None:
        user_p.last_scrape = datetime.now(timezone.utc)
        user_p.save()

    session = requests.Session()
    session.headers = {"User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"}

    url = 'https://www.theonion.com/'

    content = session.get(url, verify=False).content

    soup = BeautifulSoup(content, "html.parser")
    posts = soup.find_all('div', {'class': 'curation-module__item'})  #returns list

    for i in posts:
        link = i.find_all('a', {'class': 'js_curation-click'})[1]
        title = i.find_all('a', {'class': 'js_curation-click'})[1].text
        image_source = i.find('img', {'class':'featured-image' })['data-src']

        media_root = '/c/Users/adity/Desktop/django-scrapper/media_root'
        if not image_source.startswith(("data:image", "javascript")):
            local_filename = image_source.split('/')[-1].split("?")[0]
            r = session.get(image_source, stream=True, verify=False)
            with open(local_filename, 'wb') as f:
                for chunk in r.iter_content(chunk_size=1024):
                    f.write(chunk)

            current_image_absolute_path = os.path.abspath(local_filename)
            shutil.move(current_image_absolute_path, media_root)


        # end of stackoverflow

        new_headline = Headline()
        new_headline.title = title
        new_headline.url = link
        new_headline.image = local_filename
        new_headline.save()
    return redirect('/')

【问题讨论】:

    标签: python django


    【解决方案1】:

    您将scrape 视图的第一个参数命名为requests,这会影响requests 库的导入。

    您可以解决这个问题,但按照惯例将参数更改为 request

    def scrape(request):
    

    【讨论】:

    • 您确定更改已被采纳并且您没有运行旧版本的代码吗?如果您按照我的描述更改了方法签名,那么您显示的代码中 requests 的唯一定义是第 4 行中的 import 语句。
    • 确保你也用request.user替换了requests.user,因为这个是指请求对象而不是requests library
    • @sleblanc 很好,错过了那个。但这也暗示代码更改没有被选中,因为错误应该已更改为“AttributeError:模块'requests'没有属性'user'”
    猜你喜欢
    • 2012-07-31
    • 2019-01-19
    • 2018-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-05
    • 1970-01-01
    相关资源
    最近更新 更多