zoukankan      html  css  js  c++  java
  • Python 爬取单个网页所需要加载的地址和CSS、JS文件地址

    Python 爬取单个网页所需要加载的URL地址和CSS、JS文件地址

    通过学习Python爬虫,知道根据正式表达式匹配查找到所需要的内容(标题、图片、文章等等)。而我从测试的角度去使用Python爬虫,希望爬取到访问该网页所需要的CSS、JS、URL,然后去请求这些地址,根据响应的状态码判断是否都可以成功访问。


    代码

    '''
    Created on 2017-08-02  

    @author: Lebb
    '''
    import sys
    import urllib2
    import re
    reload(sys)
    sys.setdefaultencoding('utf-8')

    url = "https://www.szrtc.cn/"
    http = "http"
    request = urllib2.Request(url,headers=Headers)
    responsecode = None
    errorcount = 0
    itemurl = url

    def getResponse():
    try:
    response = urllib2.urlopen(request)
    except urllib2.HTTPError,he:
    print he.code
    except urllib2.URLError,ue:
    print ue.reason
    else :
    return response.read().decode('utf-8')

    def getUrl():
    html = getResponse()
    patterncss ='<link href="(.*?)"'
    patternjs = '<script src="(.*?)"'
    patternimg = '<img src="(.*?)"'
    patternpage = '<a.*?href="(.*?)"'
    patternonclick = "openQuestion.*?'(.*?)'"
    href = re.compile(patterncss, re.S).findall(html)
    href += re.compile(patternimg, re.S).findall(html)
    href += re.compile(patternpage, re.S).findall(html)
    href += re.compile(patternjs, re.S).findall(html)
    href += re.compile(patternonclick, re.S).findall(html)
    return href

    def reasonCode():
    global errorcount
    itemurl = getUrl()
    for item1 in itemurl:
    if http in item1:
    sendurl = item1
    else:
    sendurl = url + item1
    try:
    print sendurl
    responseurl = urllib2.urlopen(sendurl,timeout=8)
    except urllib2.HTTPError,he:
    responsecode = he.code
    errorcount += 1
    except urllib2.URLError,ue:
    responsecode = ue.reason
    errorcount += 1
    else:
    responsecode = responseurl.getcode()
    if(responsecode != 200):
    errorcount += 1
    print responsecode
    #return responsecode
    print errorcount

    运行的结果:
    运行截图

    错误截图:
    错误截图

    实际上这条请求复制到浏览器是可以访问的,但是Python 的urllib2访问时,因为请求带中文参数,没有进行编码转换,导致报400错误。
    尝试在代码中加入utf-8,还是没有效果,仍然报错。
    这个问题先记下来,后面去找到其他解决办法

  • 相关阅读:
    UnxUtils让windows下的dos命令变为linux下的命令
    Python多线程&进程
    Web前端工程师-优秀简历汇总
    最详细的Vuex教程
    Vue2.0 探索之路——生命周期和钩子函数的一些理解
    理解 $nextTick 的作用
    使用git rebase合并多次commit
    vim 退出命令(保存、放弃保存)
    Vue获取DOM元素样式 && 样式更改
    Vue Router的配置
  • 原文地址:https://www.cnblogs.com/jpfss/p/9233738.html
Copyright © 2011-2022 走看看