【问题标题】:Getting Empty Result from Web Scrape Using XPath使用 XPath 从 Web Scrape 中获取空结果
【发布时间】:2019-05-21 20:50:07
【问题描述】:

我使用以下代码从“最便宜”选项卡中获取票价。但是,结果我只得到“[]”。

有人可以验证我的代码和 XPath 是否正确吗?我尝试使用相对 ("//span[@class='title price']") 和绝对 XPath。另外,我应该注意,我使用的是在使用“请求”之前先呈现页面的服务。渲染应该不是问题。

page = requests.get('https://www.momondo.com/flight-search/PHL-VCE/2019-06-19-flexible/2019-06-25-flexible?sort=price_a')
sleep(5)
tree = html.fromstring(page.content)
price = tree.xpath('/html[1]/body[1]/div[1]/div[1]/div[3]/div[1]/div[1]/div[3]/div[1]/div[2]/div[1]/div[2]/div[4]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/a[1]/div[1]/div[2]/span[1]')
print(price)

【问题讨论】:

  • 您确定页面已完全加载吗?
  • 根据服务,渲染正在工作。除了渲染的潜在问题之外,代码和 XPath 对您来说是否正确?
  • 我没有看到 Cheapest 节点加载到树中,因为 page.content 没有提取航班信息。这就是您将[] 作为输出的原因。
  • 你能根据服务澄清你的意思吗?此页面动态加载,您发送的请求将仅返回带有页面“骨架”的响应,并且价格将动态加载(尝试使用 selenium 或 scrapy with splash)。加载页面后,您必须抓取表格中的所有元素。
  • 你能帮我修复代码吗?我只需要更新 XPath 吗?应该是什么?

标签: python xpath web-scraping python-requests


【解决方案1】:

网页数据由 java 脚本渲染,所以 request.get() 无法返回您期望的值。使用 selenium webdriverBeautifulSoup 检索值。

 from selenium import webdriver
 from bs4 import BeautifulSoup
 import re
 driver=webdriver.Chrome()
 driver.get("https://www.momondo.com/flight-search/PHL-VCE/2019-06-19-flexible/2019-06-25-flexible?sort=price_a&fs=flexdepart=~20190616;flexreturn=~20190622")
 soup=BeautifulSoup(driver.page_source,'html.parser')
 allprice=[price.text.replace('\xa0',' ') for price in soup.find_all('div',class_=re.compile('_A _r _s _v'))]
    print(allprice)
driver.quit()

输出:

['1,280 USD', '1,185 USD', '1,156 USD', '1,205 USD', '1,278 USD', '1,747 USD', 'N/A', '1,461 USD', '1,374 USD', '1,311 USD', '1,509 USD', '1,516 USD', '1,561 USD', '3,310 USD', '1,256 USD', '1,077 USD', '1,146 USD', '1,186 USD', '1,202 USD', '1,397 USD', '1,391 USD', '1,342 USD', '1,167 USD', '1,113 USD', '1,157 USD', '1,149 USD', '1,488 USD', '1,355 USD', '1,235 USD', '1,055 USD', '1,136 USD', '1,114 USD', '1,190 USD', '1,376 USD', '1,258 USD', '1,422 USD', '1,301 USD', '1,117 USD', '1,114 USD', '1,154 USD', '1,212 USD', '1,596 USD', '1,422 USD', '1,429 USD', '1,231 USD', '1,114 USD', '1,164 USD', '1,186 USD', '1,271 USD']

在这里你可以找到漂亮的汤文档click here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    • 2021-11-27
    相关资源
    最近更新 更多