
本文详解如何修正 readlines() 后仅处理最后一个 url 的常见错误,通过正确缩进将请求与解析逻辑置于循环体内,实现对文本文件中每个 url 的独立抓取、解析与结果写入。
在使用 file.readlines() 读取 URL 列表时,一个典型误区是:将 requests.get()、BeautifulSoup 解析及文件写入等核心逻辑写在 for 循环外部——这会导致只有最后一次迭代赋值的 url(即列表末尾的 URL)被实际处理,其余 URL 被完全忽略。
正确做法是:将整个 HTTP 请求、状态校验、HTML 解析与数据提取流程完整包裹在 for link in linksList: 循环内部,确保每条 URL 都经历一次完整的处理流水线。
以下是修正后的完整可运行代码(含关键优化):
import requests
from bs4 import BeautifulSoup
def news():
# 使用 with 语句安全读取 URL 文件(自动关闭)
with open('list.txt', 'r', encoding='utf-8') as f:
links_list = [line.strip() for line in f if line.strip()] # 去除换行符和空行
# 逐个处理每个 URL
for link in links_list:
try:
print(f"Processing: {link}")
resp = requests.get(link, timeout=10)
if resp.status_code == 200:
soup = BeautifulSoup(resp.text, 'html.parser')
# 定位目标容器(注意:若该 div 不存在,find 返回 None)
container = soup.find("div", {"class": "m-exhibitor-entry__item__body__contacts__additional__website"})
if container:
# 提取所有 标签的文本内容
websites = [a.get_text(strip=True) for a in container.find_all("a")]
# 追加写入结果文件(同样推荐用 with 管理)
with open("Websites.txt", "a", encoding="utf-8") as out_f:
for site in websites:
out_f.write(site + "\n")
print(f"✓ Extracted {len(websites)} website(s) from {link}")
else:
print(f"⚠ Warning: Target container not found on {link}")
else:
print(f"✗ Failed to fetch {link}: HTTP {resp.status_code}")
except requests.exceptions.RequestException as e:
print(f"❌ Request error for {link}: {e}")
except Exception as e:
print(f"❌ Unexpected error parsing {link}: {e}")
# 可选:添加短暂停顿,避免对服务器造成压力
# time.sleep(1)
if __name__ == "__main__":
news()✅ 关键改进说明:
立即学习“Python免费学习笔记(深入)”;
- 循环作用域正确:所有网络请求与解析逻辑均位于 for 内部,确保每条 URL 独立处理;
- 健壮性增强:加入 try/except 捕获网络异常与解析异常,防止单个失败中断整个流程;
- 资源安全:使用 with open(...) 替代裸 open(),避免文件句柄泄露;
- 数据清洗:line.strip() 清除换行符与首尾空格,if line.strip() 过滤空行;
- 容错提示:当目标 HTML 结构缺失时给出明确警告,而非抛出 AttributeError;
- 可维护性:添加日志输出,便于调试与监控进度。
⚠️ 注意事项:
- 确保 list.txt 中每行仅包含一个有效 URL(无多余空格或注释);
- 目标网站可能有反爬机制,建议设置 headers(如 User-Agent)并遵守 robots.txt;
- 若需高并发,应改用 asyncio + aiohttp,但需重写架构;本例为顺序执行,简洁可靠。
通过以上重构,你的爬虫即可稳定、清晰地遍历全部 URL,并将每个页面中匹配的网站链接逐行写入 Websites.txt。










