WebScraping 请求状态给了我 200 个没有内容的

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

我正在用美丽汤练习刮痧。在 Daijob 寻找数据分析工作时,我想抓取某些所有结果。有 70 个结果,分为 7 页,每页 10 个结果。

website = 'https://www.daijob.com/en/jobs/search_result?job_search_form_hidden=1&keywords=Data+Analyst'

for page in range(20):

        time.sleep(1)

        r = requests.get(website, params = {"page" : page+1})
        if r.status_code != 200:
            break
        else:
            html = r.content
            soup = BeautifulSoup(html, "lxml")
            print('\033[1m' + 'Web 1, page {0}'.format(page+1) + '\033[0m')

所以我们的想法是页数会不断增加,当页数达到 8 时,循环就会停止。

它在其他网站上也有效,因为一旦达到没有数据的页码,status_code 值就会变为 410 而不是 200。

但在这种情况下,无论你放置多少页(甚至可以是 100000),它都会不断给出 200 的 status_code,所以即使没有更多有用的数据可供抓取,我也无法使循环停止。

有没有更有效的方法来自动停止该循环?

python web-scraping beautifulsoup python-requests http-status-codes
1个回答
1
投票

当没有找到职位时,网站会显示以下消息:

No jobs were found that matched your search.
您可以使用此消息来查明页面是否包含任何职位。这是完整的代码:

import time
import requests
from bs4 import BeautifulSoup

website = 'https://www.daijob.com/en/jobs/search_result?job_search_form_hidden=1&keywords=Data+Analyst'

page = 0

while True:

        time.sleep(1)

        r = requests.get(website, params = {"page" : page+1})
        if 'No jobs were found that matched your search.' in r.text:
            break
        else:
            html = r.content
            soup = BeautifulSoup(html, "lxml")
            print('\033[1m' + 'Web 1, page {0}'.format(page+1) + '\033[0m')
            page += 1

输出:

Web 1, page 1
Web 1, page 2
Web 1, page 3
Web 1, page 4
Web 1, page 5
© www.soinside.com 2019 - 2024. All rights reserved.