Python如何提取Selenium爬取的酒店URL列表内的指定ID字段?
酒店ID提取实现方案(Python)
方法1:字符串分割(无额外依赖,效率最高)
针对你给出的固定URL结构,直接按规则分割字符串即可,无需导入任何第三方库:
# 替换为你实际爬取得到的URL列表 hotel_url_list = [ "https://fr.hotels.com/ho437481/?q-rooms=1...", "https://fr.hotels.com/ho629714/?q-rooms=2...", # 其余URL ] # 列表推导式直接生成ID列表 hotel_id_list = [url.split("/ho")[1].split("/")[0] for url in hotel_url_list]
运行后hotel_id_list就是仅包含酒店ID的字符串列表。
方法2:正则匹配(容错性更强)
如果存在少数URL结构有微小偏差的情况,用正则匹配ho后紧跟的连续数字,鲁棒性更高:
import re # 替换为你实际爬取得到的URL列表 hotel_url_list = [ "https://fr.hotels.com/ho437481/?q-rooms=1...", "https://fr.hotels.com/ho629714/?q-rooms=2...", # 其余URL ] # 编译匹配规则:匹配ho后面的1位及以上连续数字 id_pattern = re.compile(r"ho(\d+)") hotel_id_list = [] for url in hotel_url_list: match_res = id_pattern.search(url) if match_res: hotel_id_list.append(match_res.group(1))
该方法会自动跳过不符合结构的异常URL,不会直接抛出报错。
内容的提问来源于stack exchange,提问作者RandallCloud
相关产品推荐
相关产品推荐

