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

使用BeautifulSoup find_all()返回空列表,如何优化网页爬取代码?

解决Web Scraping获取连接器列表为空的问题

问题核心原因

目标页面的<span class="adapter-list__item-name">元素是通过JavaScript动态渲染生成的,requests库只能获取页面的静态HTML源码,无法执行JS渲染逻辑,因此找不到目标元素,返回空列表。另外你代码最后打印的是soup而非apps,但这不是导致空值的关键问题。

优化方案

方案1:用Selenium模拟浏览器加载页面

Selenium可以模拟真实浏览器行为,等待JS渲染完成后再抓取页面内容,步骤如下:

  1. 先安装Selenium和对应浏览器驱动(比如ChromeDriver)
  2. 修改代码如下:
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

# 配置无头浏览器模式(可选,无需打开可视化窗口)
chrome_options = Options()
chrome_options.add_argument('--headless=new')
chrome_options.add_argument('--disable-gpu')

driver = webdriver.Chrome(options=chrome_options)
driver.get('https://www.workato.com/integrations/salesforce')

# 显式等待目标元素加载完成,比固定sleep更稳定
WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CLASS_NAME, 'adapter-list__item-name'))
)

html_text = driver.page_source
soup = BeautifulSoup(html_text, 'lxml')

apps = soup.find_all('span', {'class':'adapter-list__item-name'})

# 输出所有连接器名称
for app in apps:
    print(app.text.strip())

driver.quit()

方案2:直接抓取动态加载的API接口

通过浏览器开发者工具(F12)的Network面板,可找到加载连接器列表的API接口,直接请求接口获取数据效率更高:

  1. 打开浏览器F12,切换到Network -> XHR/Fetch标签,刷新页面
  2. 定位返回连接器数据的API请求(比如包含adapter或integration关键词的接口)
  3. 直接请求该接口并解析JSON:
import requests

# 替换为你实际找到的API接口地址
api_url = "目标API接口URL"
headers = {
    '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',
    'Referer': 'https://www.workato.com/integrations/salesforce'
}

response = requests.get(api_url, headers=headers)
data = response.json()

# 根据API返回的JSON结构提取名称,示例需根据实际结构调整
for item in data.get('adapters', []):
    print(item.get('name'))

注意事项

  • 爬取前请遵守网站robots.txt协议和使用条款,避免触发反爬机制
  • 使用API接口时,注意请求头的模拟,部分接口可能需要携带特定参数或Cookie

内容的提问来源于stack exchange,提问作者Nhật Quang Hà

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 21:10:01