如何使用Pyshark提取HTTP/2数据包中的Stream ID
Hey there! I’ve dealt with this exact confusion when working with Pyshark and HTTP/2 packets, so let’s figure out how to get that Stream ID correctly.
Why your initial approach didn’t work
When you run print(cap[i].http2.stream), you’re seeing a human-readable summary string, not a dictionary. That’s why trying to access stream['stream_ID'] throws an error—this property isn’t structured as key-value pairs.
The correct way to extract Stream ID
Pyshark maps protocol fields to accessible attributes using snake_case naming. For HTTP/2’s Stream Identifier, the field you want is stream_id (or sometimes stream_identifier, depending on your Pyshark version).
Here’s the working code:
# Get the Stream ID directly from the http2 layer stream_id = cap[i].http2.stream_id print(f"Stream ID: {stream_id}")
How to confirm the right field name
If you ever get stuck on field names in the future, you can list all available attributes for the HTTP/2 layer with these commands:
# List all attributes of the http2 layer print(dir(cap[i].http2)) # Or get a list of all field names print(cap[i].http2.field_names)
This will show you exactly what fields are available to access—look for entries like stream_id or stream_identifier to confirm the correct name for your setup.
Example output
If your original cap[i].http2.stream output was "Stream: HEADERS, Stream ID: 85, Length 169, POST xxxxxxxxxx", running the correct code will output Stream ID: 85.
内容的提问来源于stack exchange,提问作者Nilufa Islam

