NameError: name 'container' is not defined Python Webscraping

NameError: name 'container' is not defined Python Webscraping

我目前正在尝试网络抓取。一切都很好,直到我试图缩小要从中抓取的标签的范围。每当我输入下面的代码时,就会出现上面的错误。

我以前试过这个,但是它与缩进的移动一起工作。但这一次,它没有用。我试图通过其他方式缩小范围,例如:改为 class。但是,这次它的 none 起作用了。目前卡住了。

from bs4 import BeautifulSoup as soup
import requests

link = '*insert link*'
username = 'username123'
password = 'password123'
r = requests.get(link, auth=(username, password))
page = r.content

page_soup = soup(page, "html.parser")

div = page_soup.findAll("div", {"class":"Ovx(s)"})
for table in div:
    tables = table.find("table")
    tbody = tables.find("tbody")
    container = tbody.findAll("tr", {"class":"Bgc($extraLightBlue):h"})

我也试过这个:

div = page_soup.findAll("div", {"class":"Ovx(s)"})
for table in div:
    tables = table.find("table")
    tbody = tables.find("tbody")
container = tbody.findAll("tr", {"class":"Bgc($extraLightBlue):h"})

就像我说的,这在过去可以通过调整容器变量的缩进来实现,但这次没有用。我错过了什么吗?

原因是您的代码跟在使用 container 变量的循环之后。同时

div = page_soup.findAll("div", {"class":"Ovx(s)"}

会给你一个空数组,这样我就不会进入你的循环的内部部分,因此 container 不会被定义。