我试图从Python异步返回XHR网址列表。下面是我的代码。
from PyQt5.QtWidgets import QApplication, QMainWindow, QGridLayout, QWidget, QTableWidget, QTableWidgetItem
from PyQt5.QtCore import QSize, Qt
class MainWindow(QMainWindow):
# Override class constructor
def __init__(self):
# You must call the super class method
QMainWindow.__init__(self)
self.setMinimumSize(QSize(480, 80)) # Set sizes
self.setWindowTitle("Работа с QTableWidget") # Set the window title
central_widget = QWidget(self) # Create a central widget
self.setCentralWidget(central_widget) # Install the central widget
grid_layout = QGridLayout(self) # Create QGridLayout
central_widget.setLayout(grid_layout) # Set this layout in central widget
table = QTableWidget(self) # Create a table
table.setColumnCount(3) #Set three columns
table.setRowCount(1) # and one row
# Set the table headers
table.setHorizontalHeaderLabels(["Header 1", "Header 2", "Header 3"])
#Set the tooltips to headings
table.horizontalHeaderItem(0).setToolTip("Column 1 ")
table.horizontalHeaderItem(1).setToolTip("Column 2 ")
table.horizontalHeaderItem(2).setToolTip("Column 3 ")
# Set the alignment to the headers
table.horizontalHeaderItem(0).setTextAlignment(Qt.AlignLeft)
table.horizontalHeaderItem(1).setTextAlignment(Qt.AlignHCenter)
table.horizontalHeaderItem(2).setTextAlignment(Qt.AlignRight)
# Fill the first line
table.setItem(0, 0, QTableWidgetItem("Text in column 1"))
table.setItem(0, 1, QTableWidgetItem("Text in column 2"))
table.setItem(0, 2, QTableWidgetItem("Text in column 3"))
# Do the resize of the columns by content
table.resizeColumnsToContents()
grid_layout.addWidget(table, 0, 0) # Adding the table to the grid
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec())
但是,当我运行代码时,res.request.url被打印出来,但是没有返回xhr_list,导致url为None。我的代码有问题吗?
答案 0 :(得分:1)
您的代码有两个问题。首先,intercept_response
试图构造一个列表,但是该列表始终是新创建的,并且最多只能包含一个元素。由于intercept_response
被多次调用,因此应将其附加到相同的列表中。
此外,您需要确保intercept_response
的返回值传播到main
,并从那里实际返回。例如,您可以使用闭包(内部def
)分配给外部作用域中定义的变量:
async def main():
browser = await launch(headless=False)
page = await browser.newPage()
url = []
async def intercept_response(res):
if res.request.resourceType == 'xhr':
print(res.request.url)
url.append(res.request.url)
page.on('response', intercept_response)
await page.setUserAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1')
await page.goto('https://www.iesdouyin.com/share/user/70015326114', waitUntil = 'networkidle2')
await browser.close()
return url