寫了一個小工具,有需要的自取
Github:https://github.com/851579181/xz_spider
說明
· 先知社區文章爬蟲,保存成pdf檔案
· 自己是在win10上跑的,沒太考慮其他系統,windows應該可以直接跑,其他系統需提前安裝wkhtmltopdf,然后在代碼里修改路徑,
path_wk = r'.\wkhtmltopdf\bin\wkhtmltopdf.exe'
· 采用的是逆序,從最新文章開始保存,需手動在代碼里,8590位置處,填寫最新一篇文章的頁碼,
for i in range(8590,0,-1): #逆序回圈爬取,注意這里要添加最新文章的頁碼 https://xz.aliyun.com/t/8590
try:
id = str(i)
url = "https://xz.aliyun.com/t/" + id
使用 useage
·python3環境
·pip3 install -r requirements //安裝庫
·python3 xz.py
阿里云不會封禁ip,大概一兩天就能全部爬完,5G大小,也可以用來爬取其他類似結構的網站,

專案已上傳Github:https://github.com/851579181/xz_spider
主要代碼:
# -*- coding: utf8 -*-
#Author:BlusKing
import pdfkit
import requests
import chardet
import re
path_wk = r'.\wkhtmltopdf\bin\wkhtmltopdf.exe' #pdf轉換工具 ,非windwos系統可自行安裝然后指定位置
config = pdfkit.configuration(wkhtmltopdf = path_wk)
# 設定pdf格式
options = {
'encoding': "utf-8"
}
# 也可以設定生成pdf的大小等
options = {
'encoding': "utf-8",
'page-size': 'A4',
'margin-top': '0mm',
'margin-right': '0mm',
'margin-bottom': '0mm',
'margin-left': '0mm'
}
#獲取文章名稱
def get_title(url):
header1 = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.1; ',
}
response = requests.get(url,headers=header1)
if response.status_code == 404 or str(response.status_code)[0:2] == "40": #判斷是否404,如果是,則退出
return 0
response2 = requests.get(url,headers=header1)
html_byte = response2.content
charset = chardet.detect(html_byte)['encoding'] # 探測頁面的編碼方式
result = requests.get(url,headers=header1)
if (charset.lower() == "GB2312" or charset.lower() == "gbk"):
result.encoding = 'gbk'
else:
result.encoding = 'utf-8'
content = result.text
title = re.findall('<title>(.*)</title>', content)[0]
return title
#過濾掉部分可能導致檔案創建例外的字符
def filename_filter(filename):
string1="\/:*?\"<>|"
for s1 in string1:
filename= filename.replace(s1," ")
return(filename)
if __name__ == '__main__':
try:
for i in range(8590,0,-1): #逆序回圈爬取,注意這里要添加最新文章的頁碼
try:
id = str(i)
print(id)
url = "https://xz.aliyun.com/t/" + id
print(url)
f = get_title(url)
if not f:
continue
f = filename_filter(f)
print(f)
filename = "./"+id+" :"+f + ".pdf"
pdfkit.from_url(url, filename, configuration=config,options=options) #轉換成pdf
except Exception as e:
print(str(e))
pass
except Exception as e:
print(str(e))
pass
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/232044.html
標籤:python
上一篇:我在校園自動打卡v2.0
