【问题标题】:Python requests web scraping how to detect non existent returned pages?Python请求网页抓取如何检测不存在的返回页面?
【发布时间】:2021-02-02 22:00:35
【问题描述】:

我正在抓取一些平均工资数据,以便从工作列表中制作信息图表。如果可以找到工作,比如“程序员”,那么它会给我一个代码 200,我去的页面在脚本中是一样的。

import requests

job_url: str = "https://www.ziprecruiter.com/Salaries/What-Is-the-Average-Programmer-Salary-by-State"
job_response = requests.get(job_url, timeout=10)
print(job_response)

如果“Youtuber”如下所示失败,我想向用户显示一条错误消息。但是,我仍然得到一个代码 200。手动尝试这个,他们的网站将我重定向到一个页面,如“https://www.ziprecruiter.com/Salaries/What-Is-the-Average-Youtuber-Salary-by-State? ind=null"

null_url: str = "https://www.ziprecruiter.com/Salaries/What-Is-the-Average-Youtuber-Salary-by-State"
null_response = requests.get(null_url, timeout=10)

如何在代码中确定查询是否重定向到空页面?我需要使用其他库吗?

【问题讨论】:

    标签: python web-scraping python-requests


    【解决方案1】:

    您可以禁用重定向并检查响应:

    null_url = "https://www.ziprecruiter.com/Salaries/What-Is-the-Average-Youtuber-Salary-by-State"
    null_response = requests.get(null_url, timeout=10, allow_redirects=False)
    
    if null_response.status_code == 301:
        print("Not found")
    
    if "Moved Permanently" in null_response.text:
        print("Not found")
    
    if "ind=null" in null_response.next.url:
        print("Not found")
    

    或使用重定向:

    null_url = "https://www.ziprecruiter.com/Salaries/What-Is-the-Average-Youtuber-Salary-by-State"
    null_response = requests.get(null_url, timeout=10)
    if "ind=null" in null_response.url:
        print("Not found")
    
    if null_response.history[0].status_code == 301:
        print("Not found")
    

    【讨论】:

      猜你喜欢
      • 2022-01-18
      • 1970-01-01
      • 2018-03-22
      • 2016-02-21
      • 1970-01-01
      • 2020-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多