Python中bs4解析网页:Selenium可行但Requests失效,求优化
高效获取Warframe Market物品价格的解决方案
问题背景
- 使用Selenium爬取Warframe Market中Ivara Prime蓝图的价格可以成功,但单次运行耗时约10秒,批量执行效率极低
- 使用Requests请求网页后能获取HTML内容,但无法解析到目标价格元素,返回
None
Selenium实现代码(低效但可用)
from selenium import webdriver from bs4 import BeautifulSoup options = webdriver.FirefoxOptions() options.add_argument('--headless') driver = webdriver.Firefox(options=options) driver.get('https://warframe.market/items/ivara_prime_blueprint') html = driver.page_source soup = BeautifulSoup(html, 'html.parser') price_element = soup.find('div', {'class': 'row order-row--Alcph'}) price2=price_element.find('div',{'class':'order-row__price--hn3HU'}) price = price2.text print(int(price)) driver.close()
Requests实现代码(无法解析目标元素)
import requests from bs4 import BeautifulSoup url='https://warframe.market/items/ivara_prime_blueprint' headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, 'html.parser') price_element=soup.find('div', {'class': 'row order-row--Alcph'}) price2=price_element.find('div',{'class':'order-row__price--hn3HU'}) price = price2.text print(int(price))
高效解决方案:调用官方API
Warframe Market提供了公开的API接口,直接请求结构化的JSON数据,无需等待页面渲染,速度比网页爬取快一个数量级,且不会遇到动态元素解析问题。
实现代码
import requests def get_lowest_sell_price(item_name): # 将物品名称转换为API要求的格式:小写、空格替换为下划线 api_item_name = item_name.lower().replace(' ', '_') api_url = f"https://api.warframe.market/v1/items/{api_item_name}/orders" request_headers = { 'Accept': 'application/json', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36' } response = requests.get(api_url, headers=request_headers) response_data = response.json() # 筛选所有出售订单并按价格升序排序 sell_orders = [order for order in response_data['payload']['orders'] if order['order_type'] == 'sell'] if not sell_orders: return None sell_orders.sort(key=lambda x: x['platinum']) return sell_orders[0]['platinum'] # 获取Ivara Prime蓝图的最低出售价格 lowest_price = get_lowest_sell_price('ivara prime blueprint') if lowest_price: print(f"Ivara Prime蓝图最低售价:{lowest_price} 白金") else: print("未找到该物品的出售订单")
原Requests方案失败原因
网页中的价格数据是通过前端JavaScript动态加载渲染的,直接用Requests获取的初始HTML不包含这些动态生成的元素,自然无法解析到目标价格。而API直接返回后端存储的结构化数据,无需依赖前端渲染,因此可以高效准确地提取信息。
内容的提问来源于stack exchange,提问作者spaceandtime
相关产品推荐
相关产品推荐

