使用Selenium收集Javascript下拉菜单上的每个选项



我正在尝试使用Selenium收集此页面的所有可能版本(级别、事件和季节的所有组合(的URL。我已经成功地使用driver.find_elements_by_xpath导航到正确的选项,并在保存URL之前单击它,但这非常慢,我想知道是否有更好的选择。

似乎没有任何href属性可以在不点击实际选项的情况下窃取链接。使用Select类并尝试在选项中循环更干净,但我每次都必须生成Select对象——尝试这样做:

s = Select(driver.find_element_by_xpath("//label[contains(text(), 'Level')]/../select"))
for option in s.options:
option.click()

适用于第一个选项,但随后会给我错误stale element reference: element is not attached to the page document。我被难住了——有更好的方法来收集这些链接吗?下面是我的代码片段:

driver.get("https://athletic.net/TrackAndField/Division/Event.aspx?DivID=89120&Event=1")
for i in range(0, len(driver.find_elements_by_xpath("//label[contains(text(), 'Level')]/../select/option"))):
driver.find_elements_by_xpath("//label[contains(text(), 'Level')]/../select/option")[i].click()
for j in range(0, len(driver.find_elements_by_xpath("//optgroup//option[contains(text(), 'Meters')]"))):
driver.find_elements_by_xpath("//optgroup//option[contains(text(), 'Meters')]")[j].click()
for k in range(0, len(driver.find_elements_by_xpath("//label[contains(text(), 'Season')]/..//option[contains(text(), 'Indoor')]/../option"))):
driver.find_elements_by_xpath("//label[contains(text(), 'Season')]/..//option[contains(text(), 'Indoor')]/../option")[k].click()
for l in range(0, len(driver.find_elements_by_xpath("//label[contains(text(), 'Season')]/..//option[contains(text(), '2018')]/../option"))):
driver.find_elements_by_xpath("//label[contains(text(), 'Season')]/..//option[contains(text(), '2018')]/../option")[l].click()
with open("links.txt", 'a+') as f:
f.write(driver.current_url + ";")

URL是由"DivID"标识的Location和由"Event"标识的Event的组合。

因此,您可以使用find_elements_by_xpath(复数(来查找两个下拉列表的所有options然后使用列表理解从每个CCD_ 11 中提取CCD_

location_option_list = driver.find_elements_by_xpath("//select[@ng-model='appC.locationDivId']/option")
location_values = [location_option.get_attribute('value') for location_option in location_option_list]
event_option_list = driver.find_elements_by_xpath("//select[@ng-model='appC.params.eventId']//option")
event_values = [event_option.get_attribute('value') for event_option in event_option_list]
urls = ""
for location_value in location_values:
for event_value in event_values:
urls += "https://www.athletic.net/TrackAndField/Division/Event.aspx?DivID=%s&Event=%s;" 
% (location_value, event_value)

以上代码仅适用于">高中"one_answers">"级别。您可以轻松修改它以处理">青年俱乐部"one_answers">College级别">

最新更新