Python爬虫:切换模型为'- All -'时请求失败的问题排查
问题排查与解决方法
核心问题
直接用下拉选项的显示文本- All -拼接URL是错误的:
- URL不允许包含未编码的空格,即使浏览器自动转码,后台也可能无法识别;
- 网页下拉框向服务器传递的是
<option>标签的value属性值,而非显示的文本内容。
具体解决步骤
1. 确认- All -对应的真实value值
打开目标页面,右键点击模型下拉框选择「检查」,找到<select name="model">下的对应<option>标签,查看其value属性:
<!-- 页面实际结构示例 --> <option value="" selected>- All -</option>
通常- All -对应的value是空字符串"",部分场景下可能是all。
2. 修正URL拼接逻辑
如果value是空字符串,可省略model参数或显式设为空:
# 方式1:省略model参数 link = f"https://predictioncenter.org/casp14/results.cgi?view=tables&target={target}&groups_id=" # 方式2:显式设置model为空 link = f"https://predictioncenter.org/casp14/results.cgi?view=tables&target={target}&model=&groups_id="
若value是all,则写成:
link = f"https://predictioncenter.org/casp14/results.cgi?view=tables&target={target}&model=all&groups_id="
3. 更可靠的方案:直接操作下拉框(推荐)
用Selenium直接控制下拉选择器,完全规避URL拼接的问题:
from selenium.webdriver.support.ui import Select # 进入目标页面后,定位model下拉框 model_select = Select(browser.find_element(By.NAME, "model")) # 通过显示文本选择- All - model_select.select_by_visible_text("- All -") # 或通过value值选择(已知value时) # model_select.select_by_value("")
4. 遍历逻辑优化
你当前仅获取了第一个模型选项,若要遍历所有模型,需循环model_t的每个元素,同时注意用对应选项的value而非文本拼接URL:
# 修改模型选项获取逻辑,同时保存文本和value type_model = soup.find("select",{"name":"model"}).findAll("option") model_list = [] for i in type_model: model_list.append({"text": i.text, "value": i.get("value")}) # 遍历所有目标和模型 for target in list_prot: for model in model_list: link = f"https://predictioncenter.org/casp14/results.cgi?view=tables&target={target}&model={model['value']}&groups_id=" browser.get(link) # 后续爬取逻辑...
额外提示
若必须用文本拼接URL,需先对特殊字符编码:
from urllib.parse import quote mod_encoded = quote(mod) link = f"https://predictioncenter.org/casp14/results.cgi?view=tables&target={target}&model={mod_encoded}&groups_id="
但这仅解决编码问题,核心仍需匹配option的value属性。
内容的提问来源于stack exchange,提问作者Clara HL
相关产品推荐
相关产品推荐

