如何绕过Field XPath在尝试使用Selenium&amp ;;蟒蛇?

时间:2015-11-28 19:10:59

标签: python python-2.7 selenium xpath selenium-webdriver

以下是我正在尝试搜索Orbitz.com的脚本。问题是SAME字段的XPath(让我们从FROM机场字段)不断变化。一次是fromDate_XPath = ".//*[@id='8f57e1cb92a99815ca1085ac0f6d31db']",下一次是.//*[@id='0a3807a6e50ffd4cc05eaca5b6aada17']

orbitz是否专门这样做以防止刮伤? 我想如果我用他们的网站获取他们会获得的门票的链接,因此会让我刮,不是吗?

有没有解决这个问题的方法?

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Chrome()
driver.get("http://www.orbitz.com/")
# X-PATHS FOR DIFFERENT FIELDS
fltOption_Xpath = ".//*[@id='products']/div/fieldset/div[2]/label[1]/div"
fromAir_XPath = ".//*[@id='2de60aafe0629114603daf0bc1ab52a6']"
toAir_XPath = ".//*[@id='9c64cbe5f29f6f28b64ddb9811e102b5']"
fromDate_XPath = ".//*[@id='8f57e1cb92a99815ca1085ac0f6d31db']"

toDate_XPath = ".//*[@id='aa8496535efd1aec3badf9423813fbbd']"


selFlightsOption_Element = WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_xpath(fltOption_Xpath))

selFlightsOption_Element.click()


fromAir_Element = WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_xpath(fromAir_XPath))
toAir_ELement = WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_xpath(toAir_XPath))
fromDate_Element = WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_xpath(fromDate_XPath))
toDate_Element = WebDriverWait(driver, 10).until(lambda driver: driver.find_element_by_xpath(toDate_XPath))



fromAir_Element.click()
fromAir_Element.clear()
fromAir_Element.send_keys("IAH")

toAir_Element.click()
toAir_Element.clear()
toAir_Element.send_keys("MUM")

1 个答案:

答案 0 :(得分:0)

由于输入的id属性是动态生成的,因此请不要依赖它们的定位器。

您可以切换到name - 我认为他们不会改变并且非常易读。例如,对于"从日期"输入" Hotel Only"模式:

fromDate_Element = driver.find_element_by_name("hotel.chkin")

或者出于某种原因需要XPath:

fromDate_Element = driver.find_element_by_xpath("//input[@name='hotel.chkin']")