【问题标题】:Script fails to fetch all the names available in a link脚本无法获取链接中可用的所有名称
【发布时间】:2019-12-11 17:40:20
【问题描述】:

我正在尝试获取以下链接中所有可用旅馆的名称。问题是名称是动态生成的,这就是我无法使用get 请求获取它们的原因。但是,当我发出带有适当有效负载的post 请求时,我可以从它的登录页面获取名称。当我单击show more records 按钮时出现问题,因为我可以看到负载中的一个额外字段'lr': '87' 正在添加,我无法以正确的方式使用它。

Website address

当我点击show more records按钮时增加的数字是87,227,384,457等等。

这是我尝试解析的内容(为前几个名字工作):

import requests
from bs4 import BeautifulSoup

url = 'http://hosteldunia.com/controller/search2.php'

payload={
    'address': 'hyderabad',
    'forWhom': 'Men',
    'accomodationType': 'undefined',
    'min': '2000',
    'max': '20000',
    'filter': 'single|doubleShare|tripleShare|fourShare|fiveShare'
}
session = requests.Session()
r = session.post(url,data=payload)
soup = BeautifulSoup(r.text,'lxml')
for item in soup.select("h5.hover-title-top"):
    print(item.text)

如何使用请求从该链接中获取所有名称?

【问题讨论】:

    标签: python python-3.x web-scraping


    【解决方案1】:

    这被证明是一个挑战,我必须查看 javascript 代码才能找到它。

    响应包含一个带有“more”类的 div,它的 id 是下一个 lr。我敢打赌他们没有代码审查:)

    import requests
    from bs4 import BeautifulSoup
    
    
    
    def get_next_batch(lr):
        url = 'http://hosteldunia.com/controller/search2.php'
    
        payload = {
            'address': 'hyderabad',
            'forWhom': 'Men',
            'accomodationType': 'undefined',
            'min': '2000',
            'max': '20000',
            'filter': 'single|doubleShare|tripleShare|fourShare|fiveShare',
            'lr': lr
        }
        session = requests.Session()
        r = session.post(url, data=payload)
        soup = BeautifulSoup(r.text, 'html.parser')
    
        for item in soup.select("h5.hover-title-top"):
            print(item.text)
    
        next_lr = soup.select(".more")[0]['id']
        return next_lr
    
    lr = None
    #loads next batches
    lr = get_next_batch(lr)
    lr = get_next_batch(lr)
    lr = get_next_batch(lr)
    

    【讨论】:

    • 非常好的方法@Borislav Stoilov!!!它工作得很好。我有一个小问题——当我尝试like this 时,为什么next_lr 没有更新。对此的任何评论将不胜感激。
    • 您在每次迭代时都创建了有效负载对象,并且丢失了 lr,并且每次都使用相同的 lr 调用端点。 pastebin.com/tQsKCDD7 这样做 :)
    猜你喜欢
    • 2020-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多