
本文详细介绍了如何使用python的`requests`模块模拟网页上的筛选操作,尤其当筛选条件通过http请求头而非传统的查询参数或请求体传递时。通过分析网络请求,动态获取必要的认证信息(如`location`和`key`),并将其作为自定义http头添加到会话中,最终成功从api获取到经过筛选的数据。文章提供了完整的代码示例和注意事项,帮助读者掌握此类高级网络爬取技巧。
在进行网页数据抓取时,我们经常需要模拟用户在网页上的交互行为,例如点击按钮、输入文本和应用筛选条件。虽然requests模块在处理GET请求的查询参数或POST请求的表单数据方面表现出色,但某些网站会将筛选条件或其他关键参数嵌入到HTTP请求头中。本文将以一个具体的案例——模拟USPS打印机目录网站的筛选功能为例,深入探讨如何识别并利用HTTP请求头来成功实现数据筛选。
通常,当我们需要筛选网页内容时,会尝试在requests.get()或requests.post()方法的params或data参数中设置筛选条件。然而,在某些复杂的单页应用(SPA)或API设计中,筛选逻辑可能通过以下方式实现:
本案例中,用户在USPS打印机目录网站上输入地址后,能够获取到初始搜索结果。但当尝试应用“服务类型”、“距离范围”和“排序方式”等筛选条件时,直接修改URL参数或尝试POST数据均告失败。这表明筛选参数可能隐藏在HTTP请求头中。
要解决这类问题,最关键的步骤是利用浏览器的开发者工具(通常按F12键打开)来观察网络请求。具体步骤如下:
立即学习“Python免费学习笔记(深入)”;
通过观察,我们发现当应用筛选时,实际向 https://printerdirectory.usps.com/listing/api/vendors 发送的GET请求中,包含了以下重要的自定义HTTP请求头:
其中,location和key是动态的,需要通过前期的地理编码(Geocoding)API请求获取。
在进行筛选之前,我们需要先模拟用户输入地址并获取相应的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
获取到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 []
将上述逻辑整合,形成一个完整的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模块处理将筛选条件嵌入HTTP请求头的复杂场景。掌握这种技巧,将大大提升我们处理各种复杂网页交互的能力,实现更高效、更精准的数据抓取。
以上就是Python requests高级应用:通过HTTP头实现网页筛选功能的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号