菜鸟 0.0 使用 Masonite 框架测试网上写的豆瓣爬虫

这是代码

"""A InfoController Module."""
# encoding=utf-8
import requests
from bs4 import BeautifulSoup
from masonite.request import Request
from masonite.controllers import Controller

class InfoController(Controller):
    """InfoController Controller Class."""

    def download_page(self, url):
        """获取url地址页面内容"""
        headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36'
        }
        data = requests.get(url, headers=headers).content
        return data

    def get_li(self, doc):
        # 生成解析对象
        soup = BeautifulSoup(doc, 'html.parser')
        htmls = open('test.html', 'x', -1, 'utf8')
        htmls.write(soup.get_text())
        htmls.close()

    def testPython(self):
        # 定义访问网址
        url = 'http://movie.douban.com/top250/'
        while url:
            # 请求网址,返回内容
            doc = self.download_page(url)
            self.get_li(doc)
        return 123

问题

目前是使用这个 testPython 方法之后可以生成html,但是这个方法执行完页面上之后会报错,菜鸟表示不清楚什么情况,还有这应该算是程序异常了吧

A server error occurred.  Please contact the administrator.
BUG制造者
Jason990420
最佳答案

不清楚 server error 是怎么回事, 但是至少可以看到代码中有两个问题:

  1. url 没改过, 就会一直不停的跑回路, 很快就会

    检测到有异常请求从你的 IP 发出,请 登录 使用豆瓣。

def testPython(self):
    ...
    while url:
        ...
    return 123
  1. 这个 test.html 文件以 x 模式打开, 如果第一次文件不存在, 还行, 第二次再调用, 就会出错

    FileExistsError: [Errno 17] File exists: 'test.html'ileExistsError: [Errno 17] File exists: 'test.html'

def get_li(self, doc):
    ...
     htmls = open('test.html', 'x', -1, 'utf8')
    ...
3年前 评论
小猪蹄子 (楼主) 3年前
讨论数量: 1
Jason990420

不清楚 server error 是怎么回事, 但是至少可以看到代码中有两个问题:

  1. url 没改过, 就会一直不停的跑回路, 很快就会

    检测到有异常请求从你的 IP 发出,请 登录 使用豆瓣。

def testPython(self):
    ...
    while url:
        ...
    return 123
  1. 这个 test.html 文件以 x 模式打开, 如果第一次文件不存在, 还行, 第二次再调用, 就会出错

    FileExistsError: [Errno 17] File exists: 'test.html'ileExistsError: [Errno 17] File exists: 'test.html'

def get_li(self, doc):
    ...
     htmls = open('test.html', 'x', -1, 'utf8')
    ...
3年前 评论
小猪蹄子 (楼主) 3年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!