【发布时间】:2023-03-31 21:54:01
【问题描述】:
我在抓取时遇到了这个错误:
UnboundLocalError: 赋值前引用了局部变量 'tag'
这似乎是由
引起的---> 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"))的内容
b'\n\n\n
\n html {字体系列:“Helvetica Neue”,Helvetica, Arial, sans-serif;}\n 正文 {背景颜色:#fff;填充: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 {字体大小:12px;颜色:#ccc;}\n \n\n\n \n 503 错误\n 服务不可用\n\n \n
\n HTTP 503\n \n尝试访问该网站 it.sputniknews.com 在几分钟内。
\n如果错误 重复多次,请联系站点管理。
\n \n\n \n \n IP: 107.181.177.10
\n 请求:获取 L3BvbGl0aWNhLzIwMTUwMzA4
\n 大师 冥想:MGV1SjNTaWhuUHNiblJYVU96QVpxMDB6N1hDNjU5NTU=
\n \n \n\n \n\n\n'
【问题讨论】:
标签: python web-scraping beautifulsoup