
本文详解如何修正 `readlines()` 后仅处理最后一个 url 的常见错误,通过将请求与解析逻辑正确嵌入 for 循环,实现对文本文件中每个 url 的独立抓取、解析与结果追加写入。
你的原始代码中,for link in linksList: 循环仅执行了 url = link 这一行赋值,而后续所有网络请求(requests.get(url))、HTML 解析及文件写入逻辑均位于循环外部——这意味着无论 linksList 中有多少 URL,程序只会用最后一次循环赋值的 url(即最后一行)执行一次完整流程。
要真正实现“逐个解析每个 URL”,必须将整个数据提取逻辑(包括请求、状态判断、解析、写入)全部移入 for 循环体内。以下是优化后的完整可运行代码:
import requests
from bs4 import BeautifulSoup
def news():
try:
with open('list.txt', 'r', encoding='utf-8') as f:
links_list = [line.strip() for line in f if line.strip()] # 去除空行和换行符
with open("Websites.txt", "a", encoding='utf-8') as output_file:
for link in links_list:
print(f"Processing: {link}")
try:
resp = requests.get(link, timeout=10)
if resp.status_code == 200:
soup = BeautifulSoup(resp.text, 'html.parser')
# 定位目标容器(注意:返回 None 时需判空)
container = soup.find("div", {"class": "m-exhibitor-entry__item__body__contacts__additional__website"})
if container:
for anchor in container.find_all("a"):
if anchor.text.strip():
output_file.write(anchor.text.strip() + "\n")
print(f"✓ Extracted from {link}")
else:
print(f"⚠ No target container found on {link}")
else:
print(f"✗ HTTP {resp.status_code} for {link}")
except requests.RequestException as e:
print(f"❌ Request failed for {link}: {e}")
except Exception as e:
print(f"⚠ Parsing error on {link}: {e}")
# 可选:添加小延迟,避免对服务器造成压力
# time.sleep(0.5)
if __name__ == "__main__":
news()✅ 关键改进说明:
- 使用 with open(...) 确保文件自动安全关闭;
- line.strip() 清理每行 URL 的首尾空白与换行符,避免因 \n 导致请求失败;
- 将 open("Websites.txt", "a") 提至循环外(单次打开),大幅提升 I/O 效率;
- 增加异常捕获(requests.RequestException 和通用 Exception),防止单个 URL 失败导致整个程序中断;
- 对 soup.find(...) 返回值做 if container: 判空,避免 AttributeError: 'NoneType' object has no attribute 'find_all';
- 添加清晰的状态日志(Processing / ✓ / ✗ / ⚠),便于调试与监控。
? 注意事项:
立即学习“Python免费学习笔记(深入)”;
- 确保 list.txt 中每行仅含一个有效 URL(无多余空格或注释);
- 若目标网站有反爬机制,请合理设置 headers(如 User-Agent)并遵守 robots.txt;
- 生产环境建议加入重试机制(如 tenacity 库)和并发控制(如 concurrent.futures),但初学者务必先保证单线程逻辑正确。
通过以上结构化重构,你的爬虫即可稳定、健壮地批量处理任意数量的 URL,并将所有提取结果按序追加至 Websites.txt。










