You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用BeautifulSoup抓取指定rowid=2的行数据失败,求助解决方法

问题分析

你的代码里先通过find_all("tr",{"rowid":"2"})定位目标行,但之后又重新将all_jobs赋值为soup.find_all("tr"),这直接覆盖了之前的目标行结果,导致循环输出所有<tr>的文本内容,这是无法精准定位的核心原因。

另外需要注意:部分网站的rowid可能是前端动态渲染生成的,静态请求返回的HTML里可能不存在这个属性,需要先确认页面源码中是否真的有rowid="2"的<tr>标签。

修正方案

方案1:保留精准定位逻辑,移除覆盖代码

直接使用最初的find_all结果,不要覆盖变量:

import requests
from bs4 import BeautifulSoup
headers_param = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"}
bist = requests.get("https://www.borsaistanbul.com/tr/endeks", headers=headers_param)
soup = BeautifulSoup(bist.content,"html.parser")
# 精准定位rowid=2的tr标签
target_rows = soup.find_all("tr", {"rowid": "2"})
# 遍历输出目标行文本
for row in target_rows:
    print(row.text.strip())

方案2:如果rowid不存在,通过索引定位目标行

如果静态HTML里没有rowid属性,可以直接通过索引获取目标行(注意:索引从0开始,需根据表格实际结构调整,比如排除表头行):

import requests
from bs4 import BeautifulSoup
headers_param = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"}
bist = requests.get("https://www.borsaistanbul.com/tr/endeks", headers=headers_param)
soup = BeautifulSoup(bist.content,"html.parser")
# 获取所有tr标签,取索引为2的行
all_tr = soup.find_all("tr")
if len(all_tr) > 2:
    target_row = all_tr[2]
    print(target_row.text.strip())
else:
    print("未找到目标行")

方案3:处理动态渲染页面

如果上述方法都无效,说明页面内容是JavaScript动态加载的,此时需要用工具模拟浏览器渲染:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup

chrome_options = Options()
chrome_options.add_argument("--headless=new")
chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36")

driver = webdriver.Chrome(options=chrome_options)
driver.get("https://www.borsaistanbul.com/tr/endeks")
# 等待页面加载完成
driver.implicitly_wait(5)

soup = BeautifulSoup(driver.page_source, "html.parser")
target_rows = soup.find_all("tr", {"rowid": "2"})
for row in target_rows:
    print(row.text.strip())

driver.quit()

内容的提问来源于stack exchange,提问作者Otag

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 22:40:57