Python을 사용하여 특정 블로거의 모든 블로그 게시물을 다운로드하고 pdf 형식으로 저장합니다.

기사 디렉토리

첫째, 코드 작성 아이디어 분석

둘째, 코드 단계

1. 필요한 라이브러리 가져 오기

2. 블로그 홈페이지 분석

3. 필요한 데이터 추출

4. 각 블로거 기사의 URL 탐색

많은 사람들이 파이썬을 배우고 어디서부터 시작해야할지 모릅니다.

많은 사람들이 파이썬을 배우고 기본 문법을 습득 한 후 시작할 사례를 어디서 찾을 수 있는지 모릅니다.

사례 연구를 수행 한 많은 사람들은 고급 지식을 배우는 방법을 모릅니다.

따라서이 세 가지 유형의 사람들을 위해 비디오 자습서, 전자 책 및 과정의 소스 코드를 무료로받을 수있는 좋은 학습 플랫폼을 제공 할 것입니다! ?? ¤

QQ 그룹 : 701698587

5. HTML 웹 페이지 구성

6. 폴더 생성

7. html 파일 저장

8. html 파일을 pdf 파일로 변환

3. 총 코드 및 결과

요약하자면

첫째, 코드 작성 아이디어 분석

  1. 1. 작성자 URL + 헤더 
  2. 2. 작성자의 URL이 정적 웹 페이지인지 확인 
  3. 3. 웹 페이지를 파싱하고 저자의 각 작품의 URL과 저자 이름을 가져옵니다. 
  4. 4. 각 작품의 URL에 따라 계속 방문하여 데이터 분석 
  5. 5. html 텍스트 문자열, 제목 추출 
  6. 6. 폴더 생성 
  7. 7. HTML 텍스트 저장 
  8. 8. PDF 텍스트 변환

2. 코드 단계
1. 필요한 라이브러리를 가져옵니다.
코드는 다음과 같습니다 (예제).

import requests,parsel,os,pdfkit
from lxml import etree


2. 특정 블로그의 홈페이지 분석
2.1. 언제든지 특정 블로거의 웹 사이트를 클릭합니다 (예 : "w는 강해지기를 원합니다"블로거).

2.2 개발자 도구를 클릭하여 블로거 홈페이지의 URL을 새로 고침하고로드합니다.


2.3 웹 페이지의 소스 코드를 보려면 마우스 오른쪽 버튼을 클릭하고 블로거의 홈페이지가 정적 웹 페이지임을 확인했습니다. 여기서는 웹 페이지를 구문 분석하기 위해 xpath를 선택했습니다. 물론 css 선택기, beautifulsoup 및 기타 구문 분석기를 사용할 수도 있습니다.

코드 쇼 :

    #1.author_url+headers
    author_url=input('请输入csdn博主的url:')
    headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/87.0.4280.88 Safari/537.36'}
    response = requests.get(author_url,headers=headers).text
    # 2.作者所在的url是静态网页,xpath解析每个作品url
    html_xpath = etree.HTML(response)


 

3. 필요한 데이터
추출 3.1 블로그 이름 및 모든 작품의 URL 추출


코드 쇼 :

 

   try:
        author_name = html_xpath.xpath(r'//*[@class="user-profile-head-name"]/div/text()')[0]
        # print(author_name)
        author_book_urls = html_xpath.xpath(r'//*[@class="blog-list-box"]/a/@href')
        # pprint(author_book_urls)
    except Exception as e:
        author_name = html_xpath.xpath(r'//*[@id="uid"]/span/text()')[0]
        author_book_urls = html_xpath.xpath(r'//*[@class="article-list"]/div/h4/a/@href')


요소의 xpath 경로는 직접 복사 할 수 있습니다. 여기서 사용되는 예외 처리에 대해 약간 설명하겠습니다. 사실, 홈페이지가 다른 몇몇 블로거가 있습니다. 예를 들면 다음과 같습니다.

분석 방법은 요소의 xpath 경로가 다르다는 점을 제외하고는 동일하므로 어떤 형식이든 예외 처리를 통해 작업의 URL과 이름을 추출 할 수 있습니다. 

4. 블로거의 각 기사의 URL을 탐색합니다.
4.1 각 작업 웹 페이지도 정적 웹 페이지이며 요청을 보내고 응답을 받고 파싱합니다.

코드 쇼 :

    for author_book_url in author_book_urls:
        book_res = requests.get(author_book_url,headers = headers).text
        #4.将响应分别用xpath,css选择器解析
        html_book_xpath = etree.HTML(book_res)
        html_book_css = parsel.Selector(book_res)


4.2 css 선택기는 기사의 html 텍스트를 추출하고 xpath는 기사의 제목을 추출합니다.


코드 쇼 :

        book_title = html_book_xpath.xpath(r'//*[@id="articleContentId"]/text()')[0]
        html_book_content = html_book_css.css('#mainBox > main > div.blog-content-box').get()

건설 HTML 페이지


   

    #5.拼接构造网页框架,加入文章html内容
        html =\
            '''
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title>Title</title>
            </head>
            <body>
                {}
            </body>
            </html>

6. 폴더 생성

        #6.创建博主文件夹
        if not os.path.exists(r'./{}'.format(author_name)):
            os.mkdir(r'./{}'.format(author_name))
7.保存html文件
        #6.保存html文本
        try:
            with open(r'./{}/{}.html'.format(author_name,book_title),'w',encoding='utf-8') as f:
                f.write(html)
            print('***{}.html文件下载成功****'.format(book_title))
        except Exception as e:
            continue


8. html 파일을 pdf 파일
로 변환 변환 된 파일의 물리적 상태 : wkhtmltopdf.exe 드라이버 파일 다운로드 필요!

​
        #8.转换pdf文本,导入pdfkit包
        try:
            config = pdfkit.configuration(
                wkhtmltopdf=r'D:\programs\wkhtmltopdf\bin\wkhtmltopdf.exe'
            )
            pdfkit.from_file(
                r'./{}/{}.html'.format(author_name,book_title),
                './{}/{}.pdf'.format(author_name,book_title),
                configuration=config
            )
            print(r'******{}.pdf文件保存成功******'.format(book_title))
        except Exception as e:
            continue


 

 

3. 총 코드 및 결과

# !/usr/bin/env python
# -*- coding: utf-8 -*-
 
'''
    实现目标:爬某一博主的所有博客
    1.作者url+headers
    2.看作者所在的url是否是静态网页
    3.解析网页,获取作者的每个作品的url,及作者名字
    4.根据每个作品url继续访问,然后数据分析
    5.提取html文本,标题
    6.创建多级文件夹
    7.保存html文本
    8.转换pdf文本
'''
import requests,parsel,os,pdfkit
from lxml import etree
from pprint import pprint
def main():
    #1.author_url+headers
    author_url=input('请输入csdn博主的url:')
    headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/87.0.4280.88 Safari/537.36'}
    response = requests.get(author_url,headers=headers).text
    # 2.作者所在的url是静态网页,xpath解析每个文章url
    html_xpath = etree.HTML(response)
 
    try:
        author_name = html_xpath.xpath(r'//*[@class="user-profile-head-name"]/div/text()')[0]
        # print(author_name)
        author_book_urls = html_xpath.xpath(r'//*[@class="blog-list-box"]/a/@href')
        # print(author_book_urls)
    except Exception as e:
        author_name = html_xpath.xpath(r'//*[@id="uid"]/span/text()')[0]
        author_book_urls = html_xpath.xpath(r'//*[@class="article-list"]/div/h4/a/@href')
 
    # print(author_name,author_book_urls,sep='\n')
 
    #3.遍历循环每个作品网址,请求网页
    for author_book_url in author_book_urls:
        book_res = requests.get(author_book_url,headers = headers).text
        #4.将响应分别用xpath,css选择器解析
        html_book_xpath = etree.HTML(book_res)
        html_book_css = parsel.Selector(book_res)
        book_title = html_book_xpath.xpath(r'//*[@id="articleContentId"]/text()')[0]
        html_book_content = html_book_css.css('#mainBox > main > div.blog-content-box').get()
 
        #5.拼接构造网页框架,加入文章html内容
        html =\
            '''
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title>Title</title>
            </head>
            <body>
                {}
            </body>
            </html>

 

추천

출처blog.csdn.net/Python_kele/article/details/115038240