记录python爬取某编程网站内容

记录一下python爬取某编程网站

代码:

注释写得太多反而觉得很混乱。

新手,突发兴趣,递归下载网页内容,来学习一下python的常用操作。

以下代码不包含对图片之类的处理。

下载完成以后,放在nginx下跑,怎么也不能让代码像原网站一样上色,使用fiddler一分析,才发现少下载了一个js文件。奈何本人对js不熟,还找不到加载那个js的地方,只好自己手动下载了。

http://localhost/templets/new/script/jquery.snippet.js

域名显然是你爬取网站的域名

#!/usr/bin/python
# -*- coding:utf-8 -*-

from bs4 import BeautifulSoup
from urllib.parse import urlparse
import requests
import os


def createDir(path,host,data=''):
    originalPath = os.getcwd() #每次记录本地网站的根目录,创建文件夹,文件后进行恢复
    # print("original = ",originalPath)
    arr = path.split('/')
    arr.pop(0)  #去掉域名后面的第一个/
    lens = len(arr)
    if lens == 1:
        print("only one")   #这里没有遇见,要是其他网站有遇见,就要自己处理了
        return
    filename = arr[lens-1]
    if filename.find('&') !=-1: #这里仅针对这个网站做的处理,去掉 主要是什么.php&,直接不处理
        return
    index = filename.find('?')  #某些资源文件比如hello.js?v=1234 保存文件不能带后面的东西
    if index != -1:
        filename = filename[0:index]
    arr.pop(lens-1)
    for dir in arr:
        if dir == '' or dir.find('.')!=-1:    #一些处理
            continue
        if not os.path.exists(dir): #已有的文件夹,就不能再创建了
            os.mkdir(dir)
            os.chdir(os.getcwd() + "/" + dir)   #创建文件夹,进行切换路径
        else:
            os.chdir(os.getcwd() + "/" + dir)
    # file = open(filename,"w",encoding='utf-8')
    file = open(filename,'wb')  #建议使用wb,上面的会添加很多换行符
    #没有数据就要请求网页,其实只有copyWeb那个url才有数据,减少get请求
    if data == '':
        url = host + path
        # print(url)
        data = requests.get(url)
        data = data.content
        # soup = BeautifulSoup(data, "html.parser")
        # data = soup.prettify()  #资源文件,比如js/css之类的,解析成str类型,直接写文件就可以了
    # else:
    #     file.close()
    #     file = open(filename,'w',encoding='utf-8')  #除了第一个index.html,其他的,都用wb
    file.write(data)
    file.close()
    os.chdir(originalPath)  #最后恢复路径

    if filename.find("css")!=-1:    #css文件,再处理里面的font文件
        print(path)
        soup = BeautifulSoup(data, "html.parser")
        data = soup.prettify()  #资源文件,比如js/css之类的
        last = path.rfind('/')
        prefix = path[0:last]
        last = prefix.rfind('/')
        prefix = prefix[0:last]     #因为是../,所以需要恢复前缀
        data = data.split('\n')
        for url in data:
            if url.find("url") != -1:
                # print(url)
                left = url.find('(')
                right = url.find(')')
                temp = url[left + 4:right - 1]
                # print(temp)
                newurl = prefix + temp
                index = newurl.find('?')  # 某些资源文件比如hello.js?v=1234 保存文件不能带后面的东西
                if index != -1:
                    newurl = newurl[0:index]
                print(newurl)
                createDir(newurl,host)
def copyWeb(url):
    data = requests.get(url)
    link = urlparse(url)
    host = link.hostname
    head = link.scheme + "://" + host   #保存一下协议+域名
    if not os.path.exists(host):
        os.mkdir(host)  #创建站点根目录
    os.chdir(host)

    path = link.path
    data = data.content
    soup = BeautifulSoup(data, "html.parser")

    createDir(path,head,data)    #先创建index.html,只有这里调用createDir才会提供数据

    data = soup.prettify()
    #其他的数据
    link = soup.find_all('link')
    for links in link:
        # print(links['href'])
        createDir(links['href'],head)   #实际上是自己分析尝试,这样能取出css文件的路径,进行保存

    script = soup.find_all('script',attrs = {'src' : True}) #soup太强了,这个是获取javascript文件的路径
    for scripts in script:
        createDir(scripts['src'],head) #同理,取出js的路径,进行get保存

    href = soup.find_all('div',attrs = {'id' : 'contents-detail'})  #这是分析网站结构得出的

    soup = BeautifulSoup(str(href),"html.parser")   #因为本人对soup用法不太熟,所以分两次得出每一章内容的url

    href = soup.find_all('a')
    for hrefs in href:
        if str(hrefs['href']).find('html') != -1:   #这里去掉一些章节
            createDir(hrefs['href'],head)
    return

url = 'http://xxx.biancheng.net/csharp/index.html'
copyWeb(url)

趁热打铁,换一个更知名的网站。
#!/usr/bin/python
# -*- coding:utf-8 -*-

from bs4 import BeautifulSoup
from urllib.parse import urlparse
import requests
import os

fixAddress = []
def createDir(path,host,data=''):
    global fixAddress
    if path.find("http")!=-1:
        fixAddress.append(path)
        return
    originalPath = os.getcwd() #每次记录本地网站的根目录,创建文件夹,文件后进行恢复
    # print("original = ",originalPath)
    path = path.replace("//","/")
    arr = path.split('/')
    arr.pop(0)  #去掉域名后面的第一个/
    lens = len(arr)
    if lens == 1:
        print("only one")   #这里没有遇见,要是其他网站有遇见,就要自己处理了
        return
    # print("path ",path," ",lens)
    filename = arr[lens-1]
    if filename.find('&') !=-1: #这里仅针对这个网站做的处理,去掉 主要是什么.php&,直接不处理
        return
    index = filename.find('?')  #某些资源文件比如hello.js?v=1234 保存文件不能带后面的东西
    if index != -1:
        filename = filename[0:index]
    arr.pop(lens-1)
    for dir in arr:
        if dir == '' or dir.find('.')!=-1:    #一些处理
            continue
        if not os.path.exists(dir): #已有的文件夹,就不能再创建了
            os.mkdir(dir)
            os.chdir(os.getcwd() + "/" + dir)   #创建文件夹,进行切换路径
        else:
            os.chdir(os.getcwd() + "/" + dir)
    # file = open(filename,"w",encoding='utf-8')
    file = open(filename,'wb')  #建议使用wb,上面的会添加很多换行符
    #没有数据就要请求网页,其实只有copyWeb那个url才有数据,减少get请求
    if data == '':
        url = host + path
        # print(url)
        data = requests.get(url)
        data = data.content
        # soup = BeautifulSoup(data, "html.parser")
        # data = soup.prettify()  #资源文件,比如js/css之类的,解析成str类型,直接写文件就可以了
    # else:
    #     file.close()
    #     file = open(filename,'w',encoding='utf-8')  #除了第一个index.html,其他的,都用wb
    file.write(data)
    file.close()
    os.chdir(originalPath)  #最后恢复路径

    if filename.find("css")!=-1:    #css文件,再处理里面的font文件
        print(path)
        soup = BeautifulSoup(data, "html.parser")
        data = soup.prettify()  #资源文件,比如js/css之类的
        last = path.rfind('/')
        prefix = path[0:last]
        last = prefix.rfind('/')
        prefix = prefix[0:last]     #因为是../,所以需要恢复前缀
        data = data.split('\n')
        for url in data:
            if url.find("url") != -1:
                # print(url)
                if url.find("{")!=-1:
                    continue
                left = url.find('(')
                right = url.find(')')
                temp = url[left + 4:right - 1]
                # print(temp)
                newurl = prefix + temp
                index = newurl.find('?')  # 某些资源文件比如hello.js?v=1234 保存文件不能带后面的东西
                if index != -1:
                    newurl = newurl[0:index]
                print(newurl)
                createDir(newurl,host)
def copyWeb(url):
    data = requests.get(url)
    link = urlparse(url)
    host = link.hostname
    head = link.scheme + "://" + host   #保存一下协议+域名
    if not os.path.exists(host):
        os.mkdir(host)  #创建站点根目录
    os.chdir(host)

    path = link.path
    data = data.content
    soup = BeautifulSoup(data, "html.parser")

    createDir(path,head,data)    #先创建index.html,只有这里调用createDir才会提供数据

    data = soup.prettify()

    #其他的数据
    link = soup.find_all('link',attrs={'rel':"stylesheet"})
    for links in link:
    #     print(links['href'])
        createDir(links['href'],head)   #实际上是自己分析尝试,这样能取出css文件的路径,进行保存

    script = soup.find_all('script',attrs = {'src' : True}) #soup太强了,这个是获取javascript文件的路径
    for scripts in script:
        # print(scripts['src'])
        createDir(scripts['src'],head) #同理,取出js的路径,进行get保存

    href = soup.find_all('div',attrs = {'id' : 'leftcolumn'})  #这是分析网站结构得出的

    soup = BeautifulSoup(str(href),"html.parser")   #因为本人对soup用法不太熟,所以分两次得出每一章内容的url

    href = soup.find_all('a')
    # print(link.path)
    index = path.rfind("/")
    prefix = path[0:index+1]
    for hrefs in href:
        # print(hrefs['href'])
        if hrefs['href'].find("/")==-1:
            temPath = prefix + hrefs['href']
            createDir(temPath, head)
        else:
            createDir(hrefs['href'], head)
        # if str(hrefs['href']).find('html') != -1:   #这里去掉一些章节
        #     createDir(hrefs['href'],head)

url = 'https://www.runoob.com/python3/python3-tutorial.html'
copyWeb(url)
print(fixAddress)

美中不足的是,这里面很多决定地址的js。不是太好处理。
好在,那些js好像不影响html页面的显示。

posted @ 2022-04-08 22:16  念秋  阅读(57)  评论(0编辑  收藏  举报