网页爬虫技术问题:提取链接参数、多表格数据提取及遍历方法
网页表格爬取优化方案
问题背景
需爬取网页中两个表格的三类信息:
- 参考编号(链接中的
CENSUS_NUM参数值) - 公司名称
- 城市与州
输入输出示例
输入HTML片段:
<td><a href="TractorCo.cfm?CENSUS_NUM=587357">SALVAGE YARD</a> / ANYWHERE USA</td>
当前输出:
SALVAGE YARD ANYWHERE, USA
期望输出:
587357 SALVAGE YARD ANYWHERE, USA
原代码
link ="" for a in tbl[0].find_all('td'): str_cells = str(a) str_href = str_cells.strip('TractorCo.cfm?CENSUS_NUM=') cleantext = BeautifulSoup(str_cells, "lxml").get_text() #remove html jargon cleantext=' '.join(cleantext.split()) #remove excess spaces cleantext=cleantext.replace(" /", "") clean_list = [] clean_list = cleantext print(clean_list)
解决方案
1. 提取CENSUS_NUM参数值
放弃字符串截取的不可靠方式,利用BeautifulSoup解析标签属性,结合urllib.parse解析URL参数:
from urllib.parse import urlparse, parse_qs # 遍历目标表格的td元素 for td in tbl[0].find_all('td'): # 提取CENSUS_NUM census_num = "" a_tag = td.find('a') if a_tag and 'href' in a_tag.attrs: parsed_url = urlparse(a_tag['href']) query_params = parse_qs(parsed_url.query) census_num = query_params.get('CENSUS_NUM', [''])[0] # 清理文本并调整格式 cleantext = td.get_text(strip=True) cleantext = ' '.join(cleantext.split()).replace(" /", "") cleantext = cleantext.replace(" USA", ", USA") # 拼接输出 print(f"{census_num} {cleantext}" if census_num else cleantext)
2. 遍历页面所有表格的最优方式
直接用BeautifulSoup获取所有表格,逐层遍历行与单元格,逻辑清晰且适配性强:
# 获取页面全部表格 all_tables = soup.find_all('table') # 遍历每个表格 for table in all_tables: # 遍历表格每行 for row in table.find_all('tr'): # 遍历行内每个单元格 for td in row.find_all('td'): # 复用上述提取CENSUS_NUM和清理文本的逻辑 census_num = "" a_tag = td.find('a') if a_tag and 'href' in a_tag.attrs: parsed_url = urlparse(a_tag['href']) query_params = parse_qs(parsed_url.query) census_num = query_params.get('CENSUS_NUM', [''])[0] cleantext = td.get_text(strip=True) cleantext = ' '.join(cleantext.split()).replace(" /", "").replace(" USA", ", USA") print(f"{census_num} {cleantext}" if census_num else cleantext)
优化说明
- 避免重复解析:直接调用
td.get_text(),无需将td转为字符串再重新解析HTML,提升效率 - 参数解析更可靠:用
urllib.parse处理URL参数,不受参数顺序、额外参数影响 - 结构化遍历:从表格到行再到单元格的层级遍历,适配不同表格结构,扩展性强
内容的提问来源于stack exchange,提问作者Justice
相关产品推荐
相关产品推荐

