Python requests发送post请求时data参数无效 爬虫无法获取数据求助
问题排查及解决方法
- 核心错误:请求方法不匹配。你需要发送POST请求,但代码中调用的是
requests.get(),GET请求不会将data参数中的内容放入请求体传输,仅会将参数拼接在URL后,不符合目标接口的参数接收规则,自然无法得到正确返回。将对应代码修改为requests.post()即可修复该问题。 - 其他潜在问题:
- 硬编码的会话Cookie存在有效期限制,你之前抓包得到的
PHPSESSID等Cookie会随时间过期,建议先通过GET请求访问目标站点首页动态获取最新Cookie,再携带Cookie调用数据接口,避免因Cookie失效导致请求失败。 - 目前你直接将二进制的
req.content转为字符串写入文件,若接口返回标准JSON格式,可先判断请求状态码为200后调用req.json()解析内容,再做存储,避免出现乱码、额外转义字符的问题。 - 部分站点的POST接口要求指定
Content-Type为application/x-www-form-urlencoded,requests.post默认会使用该请求头,若后续仍有问题可以手动在headers中添加该字段确认。
- 硬编码的会话Cookie存在有效期限制,你之前抓包得到的
修正后的核心代码片段
import requests def print_hi(start): headers = { 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0', # 可选:显式指定Content-Type 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } url = "https://lite.ip2location.com/get-range.json?country=AE" cookies = {"PHPSESSID":"h90gasrdrruf0t4sqrvlr6onnh", "_gcl_au":"1.1.459429746.1630175151", "_ga_4JBHWLMXXQ": "GS1.1.1630175150.1.0.1630175152.0", "_ga":"GA1.2.1147785651.1630175151", "_gid":"GA1.2.1338887027.1630175152" } data = {'draw': 3, 'columns[0][data]':0, 'columns[0][name]' :'', 'columns[0][searchable]' : 'true', 'columns[0][orderable]' : 'false', 'columns[0][search][value]' :'', 'columns[0][search][regex]' :'false', 'columns[1][data]':1,'columns[1][name]':'','columns[1][searchable]':'true', 'columns[1][orderable]':'false', 'columns[1][search][value]': '', 'columns[1][search][regex]':'false', 'columns[2][data]':2, 'columns[2][name]':'', 'columns[2][searchable]':'true', 'columns[2][orderable]':'false', 'columns[2][search][value]':'', 'columns[2][search][regex]':'false', 'order[0][column]' :0, 'order[0][dir]':'asc', 'start': int(start), 'length':25, 'search[value]':'', 'search[regex]': 'false'} # 改为post请求 req = requests.post(url, data=data, headers=headers, cookies=cookies) print(data) if req.status_code == 200: with open("ps-ip-ranges.txt", "a", encoding="utf-8") as fi: # 可改为req.json()获取结构化数据 fi.write(str(req.content.decode('utf-8'))+"\n") print("[+]\t"+str(start)+"\t is saved.") if __name__ == '__main__': for i in range(25,250000,25): print_hi(i)
内容的提问来源于stack exchange,提问作者elavakam z
相关产品推荐
相关产品推荐

