从没有选项或选择标签的 Selenium 下拉列表中获取所有组合

0 投票
1 回答
1187 浏览
提问于 2025-04-21 02:59

我正在使用Selenium这个工具来处理一个网站,链接是:http://calstate-la.bncollege.com/webapp/wcs/stores/servlet/TBWizardView?catalogId=10001&langId=-1&storeId=30556

我想从这个网站的下拉菜单中获取所有可能的部门、课程和班级的组合。现在我遇到的主要问题是,我不知道怎么从下拉菜单中获取这些值。

根据其他类似问题的讨论,他们提到了一些使用select标签和option标签的解决方案。但是,当我查看这个页面的源代码时,发现下拉菜单并没有这些标签。

所以我需要帮助,想知道如何在我的特殊情况下从下拉菜单中获取所有组合。另外,我想提一下,我是用Python来做这个。

1 个回答

2

其实我尝试过用 selenium 来解决这个问题,但因为页面是异步加载的,而且有些下拉框是“伪造”的,所以很快就变得很麻烦(这是我目前的进展)。

这里有一个替代的方法,使用 requestsBeautifulSoup(完全不需要浏览器)。

这个方法的核心思想是模拟那些填充下拉框的请求:

from bs4 import BeautifulSoup
import requests

CATALOG = 10001
STORE = 30556

url = 'http://calstate-la.bncollege.com/webapp/wcs/stores/servlet/TBWizardView?catalogId={catalog}&langId=-1&storeId={store}'.format(catalog=CATALOG,
                                                                                                                                     store=STORE)
xhr_url = 'http://calstate-la.bncollege.com/webapp/wcs/stores/servlet/TextBookProcessDropdownsCmd'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.94 Safari/537.36'}

session = requests.Session()
response = session.get(url, headers=headers)
soup = BeautifulSoup(response.content)

campus = soup.find('input', attrs={'name': 'campus1'}).get('value')
book_row = soup.find('div', class_='bookRowContainer')

params = {
    'campusId': campus,
    'deptId': '',
    'courseId': '',
    'sectionId': '',
    'storeId': STORE,
    'catalogId': CATALOG,
    'langId': '-1',
    'dropdown': 'term'
}

terms = book_row.select('li.termOption')
for term in terms:
    params['termId'] = term.get('data-optionvalue')
    response = session.post(xhr_url, params=params, headers=headers)
    print response.content

这段代码会以 JSON 格式打印出所有学期的所有系别。

比如说,2014年秋季:

[
    {"categoryName":"AAAS","categoryId":"63420700","categoryIdentifier":"670_1_F14_4","title":"AAAS"},
    {"categoryName":"ACCT","categoryId":"63420752","categoryIdentifier":"670_1_F14_5","title":"ACCT"},
    ...
]

还有2014年夏季:

[
    {"categoryName":"AAAS","categoryId":"63007512","categoryIdentifier":"670_1_A14_4","title":"AAAS"},
    {"categoryName":"ACCT","categoryId":"63007490","categoryIdentifier":"670_1_A14_5","title":"ACCT"},
    ...
]

留给你自己去完成 CourseSection 的部分作为作业。

希望这对你有帮助。

撰写回答