Python执行报错ValueError: No tables found matching pattern求解决
解决pandas.read_html匹配Q1表格时抛出ValueError的问题
问题背景
此前运行正常的WNBA数据爬取脚本,目前虽能成功将Q1表格写入CSV文件,但会抛出ValueError: No tables found matching pattern错误,导致后续爬取代码中断,需单独分段执行后续脚本。
爬取脚本代码
import pandas as pd f = open("G:\WNBA\wnba_id.txt", "r") print(f) for id in f: matchid.append(id) _url_template = "https://www.basketball-reference.com/wnba/boxscores/{}" for x in matchid: formatted_url = _url_template.format(x) print(formatted_url) df=pd.read_html(formatted_url, match='(Q1)') for i in df: new=i.assign(match_id=x) new.to_csv("G:\WNBA\wnba_Q1.csv", mode='a', header=False)
错误信息
ValueError: No tables found matching pattern
解决办法
1. 修正正则匹配逻辑
(Q1)中的括号是正则表达式的特殊符号,会被解析为分组而非字面字符,导致匹配失效。可通过两种方式修正:
- 转义特殊字符:使用转义符匹配字面括号
df = pd.read_html(formatted_url, match='\(Q1\)') - 关闭正则匹配:将
regex参数设为False,直接匹配字符串df = pd.read_html(formatted_url, match='(Q1)', regex=False)
2. 清理ID中的换行符
从文本文件读取的ID可能包含换行符\n,拼接后会生成无效URL,导致部分页面爬取失败。读取时需去除换行符:
for id in f: matchid.append(id.strip()) # 移除首尾空白字符与换行符
3. 添加异常捕获机制
为避免单个页面匹配失败导致整个脚本中断,用try-except包裹爬取逻辑,跳过异常页面继续执行:
for x in matchid: formatted_url = _url_template.format(x) print(formatted_url) try: df = pd.read_html(formatted_url, match='(Q1)', regex=False) for i in df: new = i.assign(match_id=x) new.to_csv(r"G:\WNBA\wnba_Q1.csv", mode='a', header=False) except ValueError as e: print(f"页面{x}匹配Q1表格失败: {e}") continue
4. 修正Windows路径转义问题
Windows系统中路径的\会被当作转义字符,建议使用原始字符串或双反斜杠避免解析错误:
# 读取文件时 f = open(r"G:\WNBA\wnba_id.txt", "r") # 写入CSV时 new.to_csv(r"G:\WNBA\wnba_Q1.csv", mode='a', header=False)
内容的提问来源于stack exchange,提问作者eestlane
相关产品推荐
相关产品推荐

