我在使用 python selenium 进行多下拉 url 检索算法时遇到了很大的麻烦。简而言之,我希望我的程序转到链接(https://www.xpel.com/clearbra-installers/)并迭代三个位置下拉列表中的每一个以检索每个可能的最终链接(即) https://www.xpel.com/clearbra-installers/united-states/california/bakersfield)。
我尝试了几种不同的方法来执行此操作,包括单击表格选项、迭代下拉列表,甚至收集每个下拉选项的数据帧,然后创建 url 并转到这些链接。然而,我尝试解决这个问题,但我总是遇到与等待时间和“未找到陈旧元素”错误相关的障碍。
这是我正在尝试抓取的html:
<select class="dealer-locator-select" id="dealer-locator-country-select" name="dealer-locator-country-select" data-action="country-select" data-filter="">
<option value=""> Region, Country or Area </option>
<option value="albania"> Albania </option>
<option value="algeria"> Algeria </option>
<option value="argentina"> Argentina </option>
<option value="armenia"> Armenia </option>
<option value="australia"> Australia </option>
<option value="austria"> Austria </option>
<option value="bahrain"> Bahrain </option>
<option value="belgium"> Belgium </option>
<option value="bosnia-and-herzegovina"> Bosnia and Herzegovina </option>
...
<option value="vietnam"> Vietnam </option>
</select>
这是我尝试过检索国家/地区的一些代码:
# set wait
delay = 10 # seconds
wait = WebDriverWait(driver, delay)
# iterate through country options
for i in range(2,96):
wait.until(EC.presence_of_element_located((By.XPATH, "//select[@id='dealer-locator-country-select']/option[" + str(i) + "]")))
country_name = driver.find_element(By.XPATH, "//select[@id='dealer-locator-country-select']/option[" + str(i) + "]").text.lower().replace(' ', '-')
country = Select(driver.find_element(By.XPATH, "//select[@id='dealer-locator-country-select']")).select_by_value(country_name)
print("done")
代码似乎可以在选择之前找到;例如,如果我只是检索国家/地区名称然后打印它,一切都会完美运行。我也尝试过使用 try/ except/finally,但我都没有运气:
# set wait
delay = 10 # seconds
wait = WebDriverWait(driver, delay)
# iterate through each country option
for i in range(2,96):
wait.until(EC.presence_of_element_located((By.XPATH, "//select[@id='dealer-locator-country-select']/option[" + str(i) + "]")))
country_name = driver.find_element(By.XPATH, "//select[@id='dealer-locator-country-select']/option[" + str(i) + "]").text.lower().replace(' ', '-')
try:
country = Select(driver.find_element(By.XPATH, "//select[@id='dealer-locator-country-select']"))
except:
sleep(5)
country = Select(driver.find_element(By.XPATH, "//select[@id='dealer-locator-country-select']"))
finally:
country.select_by_value(country_name)
print("done")
您共享的链接中的想法是根据每个下拉选项呈现一个新页面。例如,从第一个下拉列表中选择阿尔及利亚会强制浏览器打开 https://www.xpel.com/clearbra-installers/algeria。如果用户随后选择 blida 状态,则会呈现一个新页面 https://www.xpel.com/clearbra-installers/algeria/blida 等等。 因此,您必须通过您正在执行的任何操作再次重新选择所有下拉菜单。
我认为的解决方案是在每个country.select_by_value语句后添加延迟(例如5秒),然后再次重新选择下拉列表,因为页面内容已更改。
此外,在循环末尾添加延迟可能是个好主意,以确保加载动态内容/