我是 python 的新手,正在尝试学习网络抓取。按照教程,我试图从网站上提取价格,但没有打印任何内容。我的代码有什么问题?
from selenium import webdriver
chrome_path = r"C:\webdrivers\chromedriver.exe"
driver = webdriver.Chrome(chrome_path)
driver.get("https://reservations.airarabia.com/service-app/ibe/reservation.html#/fare/en/AED/AE/SHJ/KHI/07-09-2019/N/1/0/0/Y//N/N")
price = driver.find_elements_by_class_name("fare-and-services-flight-select-fare-value ng-isolate-scope")
for post in price:
print(post.text)
请您参考如下方法:
要打印第一个 title,您必须为所需的 visibility_of_element_located() 引入 WebDriverWait,您可以使用以下任一 Locator Strategies:
使用
CSS_SELECTOR:print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "isa-flight-select button:first-child span.fare-and-services-flight-select-fare-value.ng-isolate-scope"))).get_attribute("innerHTML"))使用
XPATH:print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//isa-flight-select//following::button[contains(@class, 'button')]//span[@class='fare-and-services-flight-select-fare-value ng-isolate-scope']"))).text)注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC两次背靠背执行的控制台输出:
475
You can find a relevant discussion in How to retrieve the title attribute through Selenium using Python?
结尾
根据文档:
-
get_attribute()方法获取元素的给定属性。 -
text属性返回元素的文本。 - Difference between text and innerHTML using Selenium
