使用requests库修改科廷大学网站地区设置的方法求助
问题:切换科廷大学课程页面的地区模式(Domestic/International)
我使用Python的requests库获取科廷大学化学工程本科荣誉学位课程页面(https://www.curtin.edu.au/study/offering/course-ug-chemical-engineering-major-beng-hons--mjrh-cheng/)的HTML内容时,默认返回的是Domestic(本地)地区的版本。我需要实现切换到International(国际)模式,同时也要能切换回Domestic模式,但不能使用Selenium,不过可以使用MiniRacer。
当前使用的请求代码:
def get_response(url, **kwargs): try: return requests.get(url, headers=headers, **kwargs) except Exception as e: print(f"Error : {e}\nRetrying in 5s") time.sleep(5) return get_response(url, **kwargs)
补充发现:手动切换地区时,页面中的dataCoreLayer变量里的fsIntDom值会在dom(本地)和int(国际)之间切换,但不知道如何利用这一点实现自动切换。
解决方案
1. 利用Cookie直接设置地区偏好(最简便)
多数网站会用Cookie存储用户的地区偏好,你可以通过以下步骤获取并使用对应Cookie:
- 打开浏览器手动切换到International模式,打开开发者工具(F12)→ 「Application」标签 → 「Cookies」→ 找到目标域名下与地区相关的Cookie(比如
fsIntDom),记录其值为int(切换到Domestic则值为dom)。 - 在
requests请求中添加该Cookie:# 构造地区Cookie region_cookies = { 'fsIntDom': 'int' # 切换到Domestic时改为'dom' } # 传入请求 response = get_response(url, cookies=region_cookies)
2. 用MiniRacer处理JS逻辑(Cookie方法失效时备选)
如果网站的地区切换依赖前端JS生成参数或设置Cookie,可以用MiniRacer模拟这一过程:
from miniracer import MiniRacer import re def switch_region(url, target_region='int'): # 获取初始页面HTML init_response = get_response(url) html = init_response.text # 提取包含dataCoreLayer的JS片段 js_pattern = re.search(r'<script>([\s\S]*?dataCoreLayer[\s\S]*?)</script>', html) if js_pattern: raw_js = js_pattern.group(1) # 修改fsIntDom为目标值(int/dom) modified_js = raw_js.replace("'fsIntDom': 'dom'", f"'fsIntDom': '{target_region}'") # 执行JS模拟地区切换逻辑 ctx = MiniRacer() ctx.eval(modified_js) # 构造对应Cookie并重新请求 region_cookies = {'fsIntDom': target_region} return get_response(url, cookies=region_cookies) return None # 使用示例:获取国际版页面 international_response = switch_region(url, 'int') # 获取本地版页面 domestic_response = switch_region(url, 'dom')
3. 尝试URL参数切换
部分网站支持通过URL参数指定地区,可以尝试构造带参数的URL:
# 国际版URL international_url = f"{url}?intDom=int" # 本地版URL domestic_url = f"{url}?intDom=dom" # 请求对应页面 international_response = get_response(international_url)
内容的提问来源于stack exchange,提问作者DarkZeus
相关产品推荐
相关产品推荐

