首页 > 解决方案 > 抓取时出现 UnboundLocalError

问题描述

抓取时出现此错误:

UnboundLocalError:分配前引用的局部变量“标签”

这似乎是由

---> 17 返回 tag.select_one(".b-plainlist__date").text, tag.select_one(".b-plainlist__title").text, tag.find_next(class_="b-plainlist__announce").text.strip ()

我正在使用的代码如下:

import requests
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor
import pandas as pd

daterange = pd.date_range('02-25-2015', '09-16-2020', freq='D')

def main(req, date):
    r = req.get(f"website/{date.strftime('%Y%m%d')}")
    soup = BeautifulSoup(r.content, 'html.parser')
    for tag in soup.select(".b-plainlist "):
        print(tag.select_one(".b-plainlist__date").text)
        print(tag.select_one(".b-plainlist__title").text)
        print(tag.find_next(class_="b-plainlist__announce").text.strip())
    
    return tag.select_one(".b-plainlist__date").text, tag.select_one(".b-plainlist__title").text, tag.find_next(class_="b-plainlist__announce").text.strip()


with ThreadPoolExecutor(max_workers=30) as executor:
    with requests.Session() as req:
        fs = [executor.submit(main, req, date) for date in daterange]
        allin = []
        for f in fs:
            allin.append(f.result()) # the problem should be from here
        df = pd.DataFrame.from_records(
            allin, columns=["Date", "Title", "Content"])
   

我尝试在这篇文章中应用一些更改:UnboundLocalError: local variable 'text' referenced before assignment,但我想我还没有完全理解如何修复它。

更新:这是网站的回应和内容print (soup.select("b-plainlist"))

<响应 [503]> b'\n\n\n
\n HTTP 503\n \n

\n html {font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;}\n body {background-color:#fff;padding:15px;}\n div.title {font-size:32px; font-weight:bold;line-height:1.2em;}\n div.sub-title {font-size:25px;}\n div.descr {margin-top:40px;}\n div.footer {margin- top:80px;color:#777;}\n div.guru {font-size:12px;color:#ccc;}\n \n\n\n \n 503 错误\n 服务不可用\n\n \n

尝试在几分钟内访问网站 it.sputniknews.com。

\n

如果错误重复多次,请联系站点管理。

\n \n\n \n \n IP: 107.181.177.10
\n 请求: GET L3BvbGl0aWNhLzIwMTUwMzA4
\n 大师冥想: MGV1SjNTaWhuUHNiblJYVU96QVpxMDB6N1hDNjU5NTU=
\n \n \n\n \n\n\n'

标签: pythonweb-scrapingbeautifulsoup

解决方案


尝试在 for 循环之外声明 tag=None,如下所示

def main(req, date):
r = req.get(f"website/{date.strftime('%Y%m%d')}")
soup = BeautifulSoup(r.content, 'html.parser')
tag=None
for tag in soup.select(".b-plainlist "):

当控件从未进入循环并且反过来,变量'tag'从未初始化时,会发生错误。因此,当您尝试返回 tag.select_one(".b-plainlist__date") 时,编译器会抛出 UnboundLocalError


推荐阅读