【问题标题】:Broken Link Checker Fails Head Requests断开的链接检查器失败的头请求
【发布时间】:2016-03-18 19:19:29
【问题描述】:

我正在使用 Python 3.4 构建一个断开链接检查器,以帮助确保我管理的大量文章的质量。最初我使用 GET 请求来检查链接是否可行,但是我在 ping 我正在检查的 URL 时尽量做到最好,所以我都确保我不检查经过测试的 URL 工作更多不止一次,我试图只做头部请求。

但是,我发现了一个网站,它会导致它停止。它既不抛出错误,也不打开:

https://www.icann.org/resources/pages/policy-2012-03-07-en

链接本身功能齐全。所以理想情况下,我想找到一种处理类似链接的方法。 Python 3.4 中的这段代码将重现该问题:

import urllib
import urllib.request

URL = 'https://www.icann.org/resources/pages/policy-2012-03-07-en'
req=urllib.request.Request(URL, None, {'User-Agent': 'Mozilla/5.0 (X11; Linux i686; G518Rco3Yp0uLV40Lcc9hAzC1BOROTJADjicLjOmlr4=) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36','Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8','Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3','Accept-Encoding': 'gzip, deflate, sdch','Accept-Language': 'en-US,en;q=0.8','Connection': 'keep-alive'}, method='HEAD')>>> from http.cookiejar import CookieJar
cj = CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
response = opener.open(req)

由于它不会引发错误,我真的不知道如何进一步解决这个问题,除了将其缩小到停止整个检查器的链接。如何检查此链接是否有效?

【问题讨论】:

  • 您将什么定义为断开的链接?错误 404?
  • 404, 502, 504, 403, 超时错误...基本上任何超过 200 的响应代码。如果我可以确定在浏览器中访问该页面会加载,这就是我需要做的所有事情.我不能指望它以任何其他方式理解链接是正确的。
  • 如果有帮助,对https://www.icann.org/ 的任何请求似乎都会挂起......奇怪
  • 请注意,完整的 GET 请求将成功加载此页面。因此,能够以某种方式关闭挂起时间过长的请求,然后在此事件中执行完整的 GET 请求也将非常有帮助。

标签: python python-3.4 urllib cookiejar


【解决方案1】:
From bs4 import BeautifulSoup,SoupStrainer    
import urllib2    
import requests    
import re    
import certifi    
import ssl    
ssl._create_default_https_context = ssl._create_unverified_context

def getStatus(url):
    a=requests.get(url,verify=False)
    report = str(a.status_code)
    return report


alllinks=[]
passlinks=[]
faillinks=[]
html_page = urllib2.urlopen("https://link")

soup = BeautifulSoup(html_page,"html.parser")
for link in soup.findAll('a', attrs={'href': re.compile("^http*")}):
    #print link.get('href')
    status = getStatus(link.get('href'))
    #print ('URL---->',link.get('href'),'Status---->',status)
    link='URL---->',link.get('href'),'Status---->',status
    alllinks.append(link)

    if status == '200':
        passlinks.append(link)
    else:
        faillinks.append(link)


print alllinks
print passlinks
print faillinks

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-20
    • 2016-03-03
    • 2014-01-22
    • 2017-10-22
    • 2016-10-29
    • 1970-01-01
    • 2023-01-08
    • 2021-05-10
    相关资源
    最近更新 更多