
本文详细介绍了如何使用python的`requests`模块模拟网页上的筛选操作,尤其当筛选条件通过http请求头而非传统的查询参数或请求体传递时。通过分析网络请求,动态获取必要的认证信息(如`location`和`key`),并将其作为自定义http头添加到会话中,最终成功从api获取到经过筛选的数据。文章提供了完整的代码示例和注意事项,帮助读者掌握此类高级网络爬取技巧。
在进行网页数据抓取时,我们经常需要模拟用户在网页上的交互行为,例如点击按钮、输入文本和应用筛选条件。虽然requests模块在处理GET请求的查询参数或POST请求的表单数据方面表现出色,但某些网站会将筛选条件或其他关键参数嵌入到HTTP请求头中。本文将以一个具体的案例——模拟USPS打印机目录网站的筛选功能为例,深入探讨如何识别并利用HTTP请求头来成功实现数据筛选。
1. 问题背景与挑战
通常,当我们需要筛选网页内容时,会尝试在requests.get()或requests.post()方法的params或data参数中设置筛选条件。然而,在某些复杂的单页应用(SPA)或API设计中,筛选逻辑可能通过以下方式实现:
- JavaScript动态加载: 页面内容通过JavaScript异步加载,筛选操作也由JavaScript触发,并向后端API发送请求。
- HTTP请求头传递参数: 筛选条件不作为URL查询参数或请求体的一部分,而是作为自定义HTTP请求头(Custom HTTP Headers)发送给服务器。
本案例中,用户在USPS打印机目录网站上输入地址后,能够获取到初始搜索结果。但当尝试应用“服务类型”、“距离范围”和“排序方式”等筛选条件时,直接修改URL参数或尝试POST数据均告失败。这表明筛选参数可能隐藏在HTTP请求头中。
2. 识别筛选机制:浏览器开发者工具的应用
要解决这类问题,最关键的步骤是利用浏览器的开发者工具(通常按F12键打开)来观察网络请求。具体步骤如下:
立即学习“Python免费学习笔记(深入)”;
- 打开开发者工具: 在目标网页上按F12,切换到“Network”(网络)标签页。
- 模拟用户操作: 在网页上输入搜索地址,并应用所需的筛选条件(例如选择“Printing your mailpiece”、“within 50 miles”)。
-
观察请求: 当点击“Apply Filters”按钮后,开发者工具会显示新的网络请求。我们需要仔细检查这些请求的:
- URL: 目标API的URL。
- Request Headers(请求头): 查找是否存在自定义的、与筛选条件相关的请求头。
- Query String Parameters(查询字符串参数): 检查URL中是否有筛选参数。
- Request Payload(请求负载): 检查POST请求体中是否有筛选参数。
通过观察,我们发现当应用筛选时,实际向 https://printerdirectory.usps.com/listing/api/vendors 发送的GET请求中,包含了以下重要的自定义HTTP请求头:
- radius: 表示距离范围,例如 "50"。
- type: 通常是 "key",表示通过键值对定位。
- location: 搜索的地理位置,例如 "New York City, New York, USA"。
- key: 一个动态生成的魔术键(magicKey),用于验证位置信息。
其中,location和key是动态的,需要通过前期的地理编码(Geocoding)API请求获取。
3. 动态获取 location 和 key
在进行筛选之前,我们需要先模拟用户输入地址并获取相应的location和key。这通常通过调用一个地理编码建议API来实现。
import requests
import time
# 地理编码建议API的URL
GEOSUGGEST_URL = 'https://gis.usps.com/arcgis/rest/services/locators/EDDM_Composite/GeocodeServer/suggest'
# 目标筛选API的URL
VENDORS_API_URL = 'https://printerdirectory.usps.com/listing/api/vendors'
# 初始页面URL,用于建立会话
BASE_LISTING_URL = 'https://printerdirectory.usps.com/listing/'
def get_location_and_key(session, search_address):
"""
通过地理编码建议API获取location和key。
"""
params = {
'text': search_address,
'f': 'json'
}
# 模拟浏览器User-Agent
session.headers.update({
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept': 'application/json, text/plain, */*',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-US,en;q=0.9',
'Origin': 'https://printerdirectory.usps.com',
'Referer': 'https://printerdirectory.usps.com/'
})
try:
res = session.get(GEOSUGGEST_URL, params=params)
res.raise_for_status() # 检查HTTP请求是否成功
suggestions = res.json().get('suggestions')
if suggestions:
first_suggestion = suggestions[0]
return first_suggestion['text'], first_suggestion['magicKey']
else:
print(f"未找到 '{search_address}' 的地理编码建议。")
return None, None
except requests.exceptions.RequestException as e:
print(f"获取地理编码建议时发生错误: {e}")
return None, None
4. 通过HTTP头应用筛选条件
获取到location和key后,我们就可以将它们与其他的筛选条件(如radius和type)一起,作为HTTP请求头添加到requests.Session中,然后向目标API发送请求。
def apply_filters_and_fetch_vendors(session, location, key, radius="50", service_id=1):
"""
应用筛选条件并获取供应商列表。
"""
# 设定筛选参数作为HTTP请求头
filter_headers = {
"radius": radius,
"type": "key",
"location": location,
"key": key,
# 其他可能需要的请求头
'Host': 'printerdirectory.usps.com',
'Referer': 'https://printerdirectory.usps.com/listing/',
'Origin': 'https://printerdirectory.usps.com',
'Accept': 'application/json, text/plain, */*',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-US,en;q=0.9',
}
# 更新会话的请求头
session.headers.update(filter_headers)
# 某些API可能需要一个noCache参数来防止浏览器缓存
# unixtime = int(time.time() * 1000)
# result_params = {'noCache': unixtime} # 实际测试发现此API不需要noCache参数
try:
resp = session.get(VENDORS_API_URL) # , params=result_params)
resp.raise_for_status()
vendors_data = resp.json().get('vendors', [])
filtered_vendors = []
for vendor in vendors_data:
# 假设 service_id=1 代表 'Printing your mailpiece'
if service_id in vendor.get('services', []):
filtered_vendors.append(vendor)
return filtered_vendors
except requests.exceptions.RequestException as e:
print(f"获取供应商数据时发生错误: {e}")
return []
5. 完整代码示例
将上述逻辑整合,形成一个完整的Python脚本:
import requests
import time
# 定义常量
GEOSUGGEST_URL = 'https://gis.usps.com/arcgis/rest/services/locators/EDDM_Composite/GeocodeServer/suggest'
VENDORS_API_URL = 'https://printerdirectory.usps.com/listing/api/vendors'
BASE_LISTING_URL = 'https://printerdirectory.usps.com/listing/'
def get_location_and_key(session, search_address):
"""
通过地理编码建议API获取location和key。
"""
params = {
'text': search_address,
'f': 'json'
}
# 初始请求头,用于模拟浏览器访问
initial_headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept': 'application/json, text/plain, */*',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-US,en;q=0.9',
'Origin': 'https://printerdirectory.usps.com',
'Referer': 'https://printerdirectory.usps.com/'
}
session.headers.update(initial_headers) # 更新会话的默认请求头
try:
res = session.get(GEOSUGGEST_URL, params=params)
res.raise_for_status() # 检查HTTP请求是否成功
suggestions = res.json().get('suggestions')
if suggestions:
first_suggestion = suggestions[0]
return first_suggestion['text'], first_suggestion['magicKey']
else:
print(f"未找到 '{search_address}' 的地理编码建议。")
return None, None
except requests.exceptions.RequestException as e:
print(f"获取地理编码建议时发生错误: {e}")
return None, None
def apply_filters_and_fetch_vendors(session, location, key, radius="50", service_id=1):
"""
应用筛选条件并获取供应商列表。
Args:
session (requests.Session): 当前的requests会话。
location (str): 地理位置字符串。
key (str): 魔术键。
radius (str): 距离范围,默认为"50"英里。
service_id (int): 服务ID,默认为1 (代表'Printing your mailpiece')。
Returns:
list: 经过筛选的供应商列表。
"""
# 设定筛选参数作为HTTP请求头
filter_headers = {
"radius": radius,
"type": "key",
"location": location,
"key": key,
# 其他可能需要的请求头,确保与浏览器发出的请求一致
'Host': 'printerdirectory.usps.com',
'Referer': 'https://printerdirectory.usps.com/listing/',
'Origin': 'https://printerdirectory.usps.com',
'Accept': 'application/json, text/plain, */*',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-US,en;q=0.9',
}
# 更新会话的请求头,这些头将应用于后续的所有请求
session.headers.update(filter_headers)
try:
# 发送GET请求到供应商API
resp = session.get(VENDORS_API_URL)
resp.raise_for_status()
vendors_data = resp.json().get('vendors', [])
filtered_vendors = []
for vendor in vendors_data:
# 根据服务ID进行进一步的Python端筛选
if service_id in vendor.get('services', []):
filtered_vendors.append(vendor)
return filtered_vendors
except requests.exceptions.RequestException as e:
print(f"获取供应商数据时发生错误: {e}")
return []
if __name__ == "__main__":
search_address = 'New York City, New York, USA'
with requests.Session() as s:
# 1. 访问初始页面以建立会话和获取可能的cookie
s.get(BASE_LISTING_URL)
# 2. 获取动态的location和key
location_text, magic_key = get_location_and_key(s, search_address)
if location_text and magic_key:
print(f"成功获取到 Location: {location_text}, Key: {magic_key}")
# 3. 应用筛选条件并获取供应商数据
# 筛选条件:服务ID为1 (Printing service), 距离50英里内
filtered_vendors = apply_filters_and_fetch_vendors(
s,
location=location_text,
key=magic_key,
radius="50",
service_id=1
)
if filtered_vendors:
print(f"\n在 '{search_address}' 附近找到 {len(filtered_vendors)} 家提供打印服务的供应商 (50英里内):")
for i, vendor in enumerate(filtered_vendors, 1):
print(f"{i:>3}. {vendor['name']:<40} (ID: {vendor['id']})")
else:
print("未找到符合筛选条件的供应商。")
else:
print("无法继续,因为未能获取有效的地理位置信息。")
代码说明:
- requests.Session(): 使用会话对象非常重要。它允许在多个请求之间保持Cookie和默认请求头,模拟真实用户的浏览过程。
- get_location_and_key(): 此函数负责调用地理编码建议API。它接收requests.Session对象和搜索地址,返回location字符串和magicKey。这些值是动态的,并且是后续筛选请求的关键。
- apply_filters_and_fetch_vendors(): 此函数将筛选条件(radius、type、location、key)封装到filter_headers字典中。然后,通过session.headers.update()方法将这些自定义请求头添加到会话中。这样,后续对VENDORS_API_URL的请求就会自动带上这些筛选头。
- 服务ID筛选: 示例中,service_id=1被假定为“Printing your mailpiece”服务。实际的筛选逻辑可能需要根据API返回的数据结构进行调整。代码中在获取所有供应商数据后,进行了Python端的二次筛选,以确保只显示提供特定服务的供应商。
- 错误处理: 使用res.raise_for_status()来检查HTTP请求是否成功(状态码200),并在失败时抛出异常,方便调试。
6. 注意事项与总结
- 动态参数的重要性: location和key是动态生成的,不能硬编码。必须通过前期的API调用动态获取。
- HTTP请求头是关键: 本案例的核心在于识别出筛选条件是通过HTTP请求头传递的。在遇到传统方法无效时,务必检查请求头。
- 开发者工具是利器: 熟练使用浏览器开发者工具的“Network”标签页是进行网络爬取和API逆向工程的必备技能。它能帮助我们洞察真实的用户交互背后隐藏的HTTP请求细节。
- API稳定性: 网站的API结构可能会发生变化。如果脚本突然失效,首先应检查目标网站是否有更新,并重新分析网络请求。
- User-Agent和Referer: 模拟真实的User-Agent和Referer等请求头有助于避免被服务器识别为爬虫并阻止访问。
- 会话管理: requests.Session在处理需要保持状态(如Cookie、自定义Header)的复杂交互场景中至关重要。
通过本教程,我们学习了如何利用requests模块处理将筛选条件嵌入HTTP请求头的复杂场景。掌握这种技巧,将大大提升我们处理各种复杂网页交互的能力,实现更高效、更精准的数据抓取。









