网址的Python字符串格式

问题描述 投票:0回答:1

我正在使用BeautifulSoup废弃网页。我想将每个网址保存在列表中。但是,操作员+无法正常工作。这是代码:

for a in soup.find_all('a', class_="hotel_name_link url"):
    hotel_url = "https://www.booking.com" + a['href']
    hotels_url_list.append(hotel_url)

我必须这样做,因为a ['href']属性只获取服务器中的文件位置而不是整个URL(例如:

/hotel/es/aqua-aquamarina.es.html?label=gen173nr-1BCAEoggJCAlhYSDNYBGigAYgBAZgBCrgBB8gBDNgBAegBAZICAXmoAgM;sid=aa0d6c563b3d74f5432fb5d5b250eee4;ucfs=1;srpvid=2d5d1564170400e8;srepoch=1514343753;room1=A%2CA;hpos=15;hapos=15;dest_type=country;dest_id=197;srfid=198499756e07f93263596e1640823813c2ee4fe1X15;from=searchresults
;highlight_room=#hotelTmpl)

但是当我打印结果时,它显示以下内容:

enter image description here

如何以BeautifulSoup可以处理的方式连接网址?

python string web-scraping beautifulsoup
1个回答
1
投票

你可以使用urljoin

from urlparse import urljoin


hotel_url = urljoin("https://www.booking.com", a['href'])
© www.soinside.com 2019 - 2024. All rights reserved.