【问题标题】:Meet cookie error when crawl website that use php session抓取使用 php 会话的网站时遇到 cookie 错误
【发布时间】:2021-09-14 13:09:52
【问题描述】:

我想抓取以下页面:https://db.aa419.org/fakebankslist.php,搜索词为“sites”。

我在 python 中使用 requests 包。没有计划尝试 selenium b/c 此页面中没有 javascript,我也不需要单击任何按钮。我觉得requests包应该有爬取的能力。

对于网站本身,我猜它使用 php 发送查询词。因此,我使用 requests.post() 创建了一个 php 会话并使用 response.cookies 检索 cookie,然后在以下发布请求中将 cookie 提供给站点。代码结构如下:

#crawl 1st page with search word in url
url='https://db.aa419.org/fakebankslist.php?psearch=sites&Submit=GO&psearchtype='
response = requests.post(url)
cookies= response.cookies
print(cookies)

#crawl page 2-4
for i in range(2, 5):
    url = 'https://db.aa419.org/fakebankslist.php?start={}'.format(str(1+20*(i-1)))
    response = requests.post(url, cookies=cookies)
    cookies= response.cookies #update cookie for each page
    print(cookies)

但是,它仅适用于前 2 页。循环开始爬取第 3 页后,cookie 变为空:。我检查了第 3 页的响应,发现它是一些与我的查询词“站点”无关的随机页面。

谁能解释一下这种情况是怎么回事?如何继续抓取以下页面?提前致谢!

【问题讨论】:

    标签: php python-requests web-crawler python-requests-html python-responses


    【解决方案1】:

    我不确定您想从该网站获得什么,但我会尽力提供帮助。 可以通过这个 url 获得第一页的结果:

    https://db.aa419.org/fakebankslist.php?psearch=essa&Submit=GO&start=1

    开始键的值 1 表示出现在页面上的第一个结果。由于每页有 19 个结果要查看第二页,因此您需要将“1”切换为“21”:

    https://db.aa419.org/fakebankslist.php?psearch=essa&Submit=GO&start=21

    第二件事是您的请求应该使用 GET 方法。

    我检查了第 3 页的响应,发现它是一些与我的查询词“站点”无关的随机页面

    我认为这与网站的搜索引擎损坏有关。

    我希望这段代码有帮助:

    #crawl page 1-5
    s = requests.Session()
    for i in range(0, 5):
        url = 'https://db.aa419.org/fakebankslist.php?psearch=essa&Submit=GO start='+str(1+i*20)
        response = s.get(url)
        cookies= s.cookies #update cookie for each page
        print('For page ', i+1, 'with results from', 1+i*20, 'to', i*20+20, ', cookies are:', str(cookies))
    

    【讨论】:

    • 它有效,你正在拯救我的生命!谢谢!我应该使用 requests.Session() 创建到该网站的持久连接。我猜我得到空 cookie 的原因是,如果我使用 requests.get(url) 而不是 s.get(url),cookie 会在 1 或 2 秒后迅速过期
    猜你喜欢
    • 2019-09-27
    • 2016-09-24
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    相关资源
    最近更新 更多