Python 获取 Booking 网站酒店链接:使用 Selenium 提取所有酒店的 href
可以使用以下代码获取 Booking 网站上所有酒店的链接:
hotel_links = browser.find_elements(By.CSS_SELECTOR, 'a.e13098a59f')
hrefs = [link.get_attribute('href') for link in hotel_links]
这将获取所有带有 CSS 类名为'e13098a59f' 的链接元素,并通过循环遍历每个元素来获取其 href 属性,并将其存储在一个列表中。
解释:
hotel_links = browser.find_elements(By.CSS_SELECTOR, 'a.e13098a59f'): 找到页面中所有带有 CSS 类名为 'e13098a59f' 的链接元素。hrefs = [link.get_attribute('href') for link in hotel_links]: 使用列表推导,循环遍历hotel_links中的每个元素,获取其href属性值,并将其存储在hrefs列表中。
使用步骤:
- 确保您已安装 Selenium 库。
- 使用 Chrome 浏览器或其他支持 Selenium 的浏览器。
- 编写代码,并替换
'a.e13098a59f'为目标网站上的实际 CSS 选择器。 - 运行代码,您将获得所有酒店链接的列表。
示例:
假设您要获取 Booking 网站上的成都拖板鞋青年旅舍旅行酒店的链接,该链接的 HTML 代码如下:
<a href='https://www.booking.cn/hotel/cn/chengdu-tuo-ban-xie-qing-nian-lv-she.zh-cn.html?sid=7c0a78f8c1db56ee42ab9578d1032f13&aid=1662037&ucfs=1&arphpl=1&checkin=2023-05-18&checkout=2023-05-19&dest_id=-1900349&dest_type=city&group_adults=2&req_adults=2&no_rooms=1&group_children=0&req_children=0&hpos=1&hapos=1&sr_order=popularity&nflt=class%3D3&srpvid=663264e64fd300db&srepoch=1683382862&all_sr_blocks=49980802_298619250_0_0_0&highlighted_blocks=49980802_298619250_0_0_0&matching_block_id=49980802_298619250_0_0_0&sr_pri_blocks=49980802_298619250_0_0_0__32800&from_sustainable_property_sr=1&from=searchresults#hotelTmpl' class='e13098a59f' target='_blank' rel='noopener noreferrer' data-testid='title-link'><div data-testid='title' class='fcab3ed991 a23c043802'>POSHPACKER·成都拖板鞋青年旅舍旅行酒店(太古里春熙路地铁站店)</div><div class='e6e585da68'>在新窗口中打开</div></a>
您可以使用上述代码获取该酒店的链接。
注意:
- 网站的 HTML 结构可能会发生变化,因此您可能需要调整 CSS 选择器。
- 获取大量数据时,请注意网站的爬虫策略,不要过度频繁地访问网站。
希望这篇文章对您有所帮助!
原文地址: https://www.cveoy.top/t/topic/nR71 著作权归作者所有。请勿转载和采集!