我正在使用scrapy and beautifulsoup来获取美国不同城市所有酒店的名单。在
当我进入一个名为“旧金山酒店”的页面时,它只包含了该市250家酒店中的30家。单击“列表上的下30个”不会更改url,也不会更改排序参数。 我的问题是:我怎样才能达到250家酒店的全部名单,或者从中选择排名。谢谢。在
目前我的代码:
r = requests.get(url)
soup = BeautifulSoup(r.content,'html.parser')
headers = soup.find_all("h1",{"class":"X"})
for header in headers:
headerText = header.text
match=re.search('(.+ Hotels)',headerText)
if match:
writeHotels(soup,match.group(0))
def writeHotels(soup,location):
#create Hotels directory
hotelDir = 'Hotels/'
if not os.path.exists(hotelDir):
os.makedirs(hotelDir)
hotels = soup.find_all("a",{"class":"Y"})
name=location+'.txt'
#write hotels to file
if os.path.exists(hotelDir+name):
print 'opening file '+name+"\n"
else:
print 'creating file '+name+"\n"
file=open(hotelDir+name,'a')
for hotel in hotels:
file.write(hotel.text+"\n")
file.close()
如果您在页面源代码中查看页面底部的页码,那么每个页面都有一个唯一的url。如果你把汤打印出来,你会发现你可以抓取这个网址。如果有很多页面,它不会显示所有页面,只是一个。。。对于中间页。但是,您可以从第一个值和最后一个值计算URL(我在下面没有这样做)。以下是我使用的代码:
这是输出
^{pr2}$注意url中的
-oa###-
。这是可以改变的,你可以得到所有的后续页面。在相关问题 更多 >
编程相关推荐