【发布时间】:2020-03-31 16:51:25
【问题描述】:
我最近一直在练习我的网络抓取技巧,并偶然发现了 Fábio Neves 的这篇精彩作品:If you like to travel, let Python help you scrape the best cheap flights!
我决定尝试创建一个机器人来抓取Ryanair site,而不是像 Fábio 那样抓取“Kayak”网站。
我的做法:
我接受用户输入的“出发机场”。然后我选择提示下拉列表出现的“发件人”文本框。此下拉列表包含 234 个位置。
city_from = input('From which city? ') #Takes users input
我尝试实施的下一步是使用下拉列表中的选项查找用户输入的匹配项。然后继续单击该匹配选项。
elements_list = driver.find_elements_by_xpath('//div [@class="core-list-ref"]') ##Finds all Elements/Cities in the dropdown list
list_pos = [value for value in elements_list].index(str(city_from)) #Finds the value(city name) for each element in the dropdown list and tries to locate the position of the inputed 'airport of departure' in the list.
elements_list[list_pos].click() #I then try to select this option.
不过……
我用下面的代码好像不是所有的234个城市都出现了:
driver.find_elements_by_xpath('//div [@class="core-list-ref"]')
只有前 79 个城市出现在奥尔堡-热那亚,其他城市似乎是“隐藏的”。我发现当我手动向下滚动到下拉列表的底部并尝试重新运行它们出现的代码时。
于是我尝试实现.move_to_element(element),让机器人向下滚动到下拉列表中的最后一个机场。但这仍然只允许我滚动到第 79 机场(热那亚)。当用户输入像“苏黎世”这样的机场时,这会使我的机器人崩溃。
这是我第一次尝试抓取。我该如何克服这个问题,或者有更好的方法来选择“出发机场”。如果您需要更多详细信息,请告诉我。
【问题讨论】:
标签: python selenium web-scraping jupyter-notebook