当我在抓取时遇到网络错误时提供故障保护

时间:2020-08-09 13:20:35

标签: selenium scrapy

我目前正在制作一个刮板,用于刮除JustEat的所有外卖信息。

class UI(QMainWindow):
    def __init__(self):
        # ...
        self.pushButton.clicked.connect(self.edit_items)

    def edit_items(self):
        if not self.model.rowCount():
            return
        index = self.tableView.currentIndex()
        if index.isValid():
            row = index.row()
        else:
            row = 0

        dialog = QtWidgets.QDialog()
        dialog.setWindowTitle("Edit Window")
        layout = QtWidgets.QVBoxLayout(dialog)

        formLayout = QtWidgets.QFormLayout()
        layout.addLayout(formLayout)

        name_line = QtWidgets.QLineEdit(self.model.index(row, 0).data())
        formLayout.addRow('Name', name_line)
        name_line.setReadOnly(True)

        age_edit = QtWidgets.QSpinBox()
        formLayout.addRow('Age', age_edit)
        age_edit.setFocus()
        age_edit.setValue(self.model.index(row, 1).data())

        genders = 'M', 'F'
        gender_combo = QtWidgets.QComboBox()
        formLayout.addRow('Gender', gender_combo)
        gender_combo.addItems(genders)
        gender = self.model.index(row, 2).data()
        if gender and gender.upper() in genders:
            gender_combo.setCurrentIndex(genders.index(gender.upper()))
        else:
            gender_combo.setCurrentIndex(-1)

        updateButton = QtWidgets.QPushButton('Update')
        layout.addWidget(updateButton)
        updateButton.clicked.connect(dialog.accept)

        if not dialog.exec_():
            return

        self.model.setData(self.model.index(row, 1), age_edit.value(), 
            QtCore.Qt.EditRole)
        if gender_combo.currentIndex() >= 0:
            self.model.setData(self.model.index(row, 2), 
                gender_combo.currentText(), QtCore.Qt.EditRole)
        # submit all changes to the database
        self.model.submitAll()

但是,有时我的互联网似乎不可靠,因此我想进行一次故障保护,以防万一运行脚本时网络中断了。

这些是我的想法:

  • 我希望它继续尝试抓取相同的URL直到网络恢复,而不是跳到下一个URL。
  • 我希望它提供所有由于网络错误而未被抓取的网址的列表。

但是更喜欢第一个。预先感谢。

1 个答案:

答案 0 :(得分:1)

有一个内置的Scrapy设置,其工作原理几乎与您想要的一样:RETRY_TIMES