帮我用python爬虫爬取携程旅行的酒店名字与价格
时间: 2023-11-19 13:04:05 浏览: 52
好的,以下是使用 Python 爬虫爬取携程旅行的酒店名字与价格的代码示例:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://hotels.ctrip.com/hotel/shanghai2'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299'
}
html = requests.get(url, headers=headers).text
soup = BeautifulSoup(html, 'html.parser')
hotel_list = soup.find_all('div', class_='hotel_new_list')
for hotel in hotel_list:
name = hotel.find('a', class_='hotel_name').text.strip()
price = hotel.find('span', class_='J_price_lowList').text.strip()
print(name + ':' + price)
```
这段代码首先通过 requests 库向携程旅行网站发送请求,然后使用 BeautifulSoup 库对返回的 HTML 页面进行解析。接着,从 HTML 中找到包含酒店信息的标签,并提取出酒店的名字和价格。最后,将这些信息打印出来。
需要注意的是,网站内容的结构可能会随着时间变化而变化,因此代码可能需要根据实际情况进行相应的调整。另外,爬取网站的速度也需要合理,以免给网站造成不必要的负担。