Python爬取比比網中標標書並保存成PDF格式

前言

本文的文字及圖片來源於網絡,僅供學習、交流使用,不具備任何商業用途,若有問題請及時聯繫咱們以做處理。css

PS:若有須要Python學習資料的小夥伴能夠加點擊下方連接自行獲取html

python免費學習資料以及羣交流解答點擊便可加入python

python開發環境網絡

  • python 3.6
  • pycharm
import requests
import parsel
import pdfkit
import time

相關模塊pip安裝便可學習

目標網頁分析

在這裏插入圖片描述
一、先從列表頁中獲取詳情頁的URL地址網站

是靜態網站,能夠直接請求網頁獲取數據
在這裏插入圖片描述url

for page in range(1, 31):
    url = 'https://www.bibenet.com/mfzbu{}.html'.format(page)
    headers = {

        'Referer': 'https://www.bibenet.com/mianfei/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'
    }
    response = requests.get(url=url, headers=headers)
    selector = parsel.Selector(response.text)
    urls = selector.css('body > div.wrap > div.clearFiex > div.col9.fl > div.secondary_box > table tr .fl a::attr(href)').getall()
    for page_url in urls:
    print(page_url)

二、從詳情頁中獲取標題以及內容code

response_2 = requests.get(url=page_url, headers=headers)
selector_2 = parsel.Selector(response_2.text)
article = selector_2.css('.container').get()
title = selector_2.css('.detailtitle::text').get()

三、保存html網頁數據並轉成PDForm

html_str = """
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
{article}
</body>
</html>
"""
def download(article, title):
    html = html_str.format(article=article)
    html_path = 'D:\\python\\demo\\招標網\\文書\\' + title + '.html'
    pdf_path = 'D:\\python\\demo\\招標網\\文書\\' + title + '.pdf'
    with open(html_path, mode='wb', encoding='utf-8') as f:
        f.write(html)
        print('{}已下載完成'.format(title))
    # exe 文件存放的路徑
    config = pdfkit.configuration(wkhtmltopdf='C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe')
    # 把 html 經過 pdfkit 變成 pdf 文件
    pdfkit.from_file(html_path, pdf_path, configuration=config)

運行實現效果

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

相關文章
相關標籤/搜索