Python在没有[href]的多层网站上浏览网页

2024-05-29 03:07:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种从学生宿舍网站uniplaces获取数据的方法:https://www.uniplaces.com/en/accommodation/berlin。在

最后,我想为每一个酒店收集具体的信息,比如卧室大小、室友人数、位置。为了做到这一点,我将首先刮除所有的属性链接,然后再刮除个别链接。在

然而,即使在通过控制台并使用beauthoulsoup提取url之后,我仍然无法提取指向单独列表的url。它们似乎没有包含在a[href]中,而且我无法在html代码中识别任何其他格式的链接。在

但python也没有返回任何代码: 从bs4导入BeautifulSoup 进口urllib.请求在

resp = urllib.request.urlopen("https://www.uniplaces.com/accommodation/lisbon")
soup = BeautifulSoup(resp, from_encoding=resp.info().get_param('charset'))

for link in soup.find_all('a', href=True):
    print(link['href'])

所以我的问题是:如果链接没有包含在http://format中或引用为[href]:有没有方法提取列表的URL?在

我真的非常感谢在这方面的任何支持!在

祝你一切顺利, 汉娜


Tags: 方法代码httpscomurl列表链接www
1条回答
网友
1楼 · 发布于 2024-05-29 03:07:50

如果您查看network选项卡,您会发现一些专门针对这个url的API调用:https://www.uniplaces.com/api/search/offers?city=PT-lisbon&limit=24&locale=en_GB&ne=38.79507211908374%2C-9.046124472314432&page=1&sw=38.68769060641113%2C-9.327992453271463

它指定了位置PT lisbon以及北(ne)和西南(sw)方向。从这个文件中,你可以得到每个优惠的id,并将其附加到当前的url中,你还可以从网页上获得所有信息(价格、说明等…)

例如:

import requests

resp = requests.get(
    url = 'https://www.uniplaces.com/api/search/offers', 
    params = {
        "city":'PT-lisbon',
        "limit":'24',
        "locale":'en_GB',
        "ne":'38.79507211908374%2C-9.046124472314432',
        "page":'1',
        "sw":'38.68769060641113%2C-9.327992453271463'
    })
body = resp.json()

base_url = 'https://www.uniplaces.com/accommodation/lisbon'

data = [
    (
        t['id'],                  #offer id
        base_url + '/' + t['id'], #this is the offer page
        t['attributes']['accommodation_offer']['title'], 
        t['attributes']['accommodation_offer']['price']['amount'],
        t['attributes']['accommodation_offer']['available_from']
    )
    for t in body['data']
]

print(data)

相关问题 更多 >

    热门问题