Есть ли функция для возврата параметров списка DropDown в HTML с использованием Mechanicalsoup или BeautifulSoup? - PullRequest
0 голосов
/ 03 февраля 2020

Как видно из названия, я работаю над проектом с использованием MechanicalSoup, и мне интересно, как я могу написать функцию, которая возвращает возможные варианты для списка DropDown. Можно ли найти элемент по его имени / идентификатору, а затем вернуть параметры?

import mechanicalsoup
from bs4 import BeautifulSoup

#Sets StatefulBrowser Object to winnet then it it grabs form
browser = mechanicalsoup.StatefulBrowser()
winnet = "http://winnet.wartburg.edu/coursefinder/"
browser.open(winnet)
Searchform = browser.select_form()

#Selects submit button and has filter options listed.
Searchform.choose_submit('ctl00$ContentPlaceHolder1$FormView1$Button_FindNow')
Searchform.set('ctl00$ContentPlaceHolder1$FormView1$TextBox_keyword', input()) #Keyword Searches by Class Title. Inputting string will search by that string ignoring any stored nonsense in the page.
#ACxxx Course Codes have 3 spaces after them, THIS IS REQUIRED. Except the All value for not searching by a Department does not.
Searchform.set("ctl00$ContentPlaceHolder1$FormView1$DropDownList_Department", 'CS   ') #For Department List, it takes the CourseCodes as inputs and displays as the Full Name
Searchform.set("ctl00$ContentPlaceHolder1$FormView1$DropDownList_Term", "2020 Winter Term") # Term Dropdown takes a value that is a string. String is Exactly the Term date.
Searchform.set('ctl00$ContentPlaceHolder1$FormView1$DropDownList_MeetingTime', 'all') #Takes the Week Class Time as a String. Need to Retrieve list of options from pages
Searchform.set('ctl00$ContentPlaceHolder1$FormView1$DropDownList_EssentialEd', 'none') #takes a small string signialling the EE req or 'all' or 'none'. None doesn't select and option and all selects all coruses w/ a EE
Searchform.set('ctl00$ContentPlaceHolder1$FormView1$DropDownList_CulturalDiversity', 'none')# Cultural Diversity, Takes none, C, D or all
Searchform.set('ctl00$ContentPlaceHolder1$FormView1$DropDownList_WritingIntensive', 'none') # options are none or WI
Searchform.set('ctl00$ContentPlaceHolder1$FormView1$DropDownList_PassFail', 'none')# Pass/Faill takes 'none' or 'PF'
Searchform.set('ctl00$ContentPlaceHolder1$FormView1$CheckBox_OpenCourses', False) #Check Box, It's True or False
Searchform.set('ctl00$ContentPlaceHolder1$FormView1$DropDownList_Instructor', '0')# 0 is for None Selected otherwise it is a string of numbers (Instructor ID?)

#Submits Page, Grabs results and then launches a browser for test purposes.
browser.submit_selected()# Submits Form. Retrieves Results.
table = browser.get_current_page().find('table') #Finds Result Table
print(type(table))
rows = table.get_text().split('\n') # List of all Class Rows split by \n. 
print(type(rows))
browser.launch_browser()

1 Ответ

0 голосов
/ 13 февраля 2020

Я понял, что если я хочу опубликовать опции, я могу получить их список, выполнив:

options_list = browser.get_current_page().findAll('option') #Finds Result Table

Затем я смог использовать for-l oop для извлечения текста и базовые значения:

vlist = []
tlist = []
for option in options_list:
    value = str(option).split('"') # Splits option into chunks, value[1] is the value
    vlist.append(value[1])
    tlist.append(option.get_text())

По сути, мне удалось создать два отдельных списка, один из которых содержал текст опции, а другой содержал базовое значение. Это можно изменить, чтобы вместо этого добавить в словарь и создать набор пар ключ: значение, которые были бы более полезны в некоторых приложениях.

...