2015-10-21 68 views
0

我想从booking.com抓取数据和几乎一切正在工作,但我无法得到的价格,我读到目前为止,这是因为这些价格加载通过AJAX调用。这里是我的代码:刮python booking与Python对AJAX请求

import requests 
import re 

from bs4 import BeautifulSoup 

url = "http://www.booking.com/searchresults.pl.html" 
payload = { 
'ss':'Warszawa', 
'si':'ai,co,ci,re,di', 
'dest_type':'city', 
'dest_id':'-534433', 
'checkin_monthday':'25', 
'checkin_year_month':'2015-10', 
'checkout_monthday':'26', 
'checkout_year_month':'2015-10', 
'sb_travel_purpose':'leisure', 
'src':'index', 
'nflt':'', 
'ss_raw':'', 
'dcid':'4' 
} 

r = requests.post(url, payload) 
html = r.content 
parsed_html = BeautifulSoup(html, "html.parser") 

print parsed_html.head.find('title').text 

tables = parsed_html.find_all("table", {"class" : "sr_item_legacy"}) 

print "Found %s records." % len(tables) 

with open("requests_results.html", "w") as f: 
    f.write(r.content) 

for table in tables: 
    name = table.find("a", {"class" : "hotel_name_link url"}) 
    average = table.find("span", {"class" : "average"}) 
    price = table.find("strong", {"class" : re.compile(r".*\bprice scarcity_color\b.*")}) 
    print name.text + " " + average.text + " " + price.text 

使用Developers Tools从Chrome中我注意到,该网页发送的所有数据(包括价格)的原始响应。在处理来自这些标签之一的响应内容之后,有价格的原始值,所以为什么我无法使用脚本检索它们,如何解决它?

enter image description here

+0

检查发送的标题,可能有些东西你不会模仿你的代码 – Marged

+0

我已经添加了所有标题,但问题仍然存在。 –

+0

为什么不使用硒作为这种类型的动态网站? – SIslam

回答

0

的第一个问题是,该网站是非法的构造:一个div在你打开表和em被关闭。所以html.parser找不到包含价格的strong标签。这个你可以安装和使用lxml修复:

parsed_html = BeautifulSoup(html, "lxml") 

的第二个问题是在你的正则表达式。它没有找到任何东西。它更改为以下:

price = table.find("strong", {"class" : re.compile(r".*\bscarcity_color\b.*")}) 

现在你会发现价格。但是,有些条目不包含任何价格,因此您的print语句将引发错误。为了解决这个问题,你可以改变你的print以下几点:

print name.text, average.text, price.text if price else 'No price found' 

,请注意您可以单独领域使用Python逗号(,)进行打印,所以你不需要用+ " " +将它们串联。

+0

哇,非常感谢我也注意到,这个网站是不合格的(但我不知道这个术语;)),并试图首先使用'prettify()',但是这也导致了其他奇怪的错误,所以你的解决方案非常好,最适合我。 –