前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python协程爬虫,gevent获取网页源码打印pdf实例爬虫

Python协程爬虫,gevent获取网页源码打印pdf实例爬虫

作者头像
二爷
发布2021-09-15 11:02:02
5040
发布2021-09-15 11:02:02
举报
文章被收录于专栏:二爷记

Python协程爬虫的一个简单实例demo,使用了队列来进行数据的传递,协程的使用相比单线程会快,感觉在加大协程线的时候,速度并没有相应的加快,或者说占用的时间并没有想象中的少,可以参照使用,仅供参考和学习使用!

在进行多协程,多线程的时候避免数据错乱,还是需要使用到队列(Queue)来进行处理,通过前面的实践对比,还是发现网页访问下,还是多线程占优!

附源码参考:

代码语言:javascript
复制
#犀牛原厂
# -*- coding: utf-8 -*-
#20210827 微信:huguo00289
import requests
import random
from lxml import etree
from gevent import monkey
monkey.patch_socket()
import gevent
from gevent.queue import Queue
import time
import pdfkit


confg = pdfkit.configuration(
    wkhtmltopdf=r'D:\wkhtmltox-0.12.5-1.mxe-cross-win64\wkhtmltox\bin\wkhtmltopdf.exe') #此处替换为自己的exe地址!


# 随机获取一个请求头
def get_user_agent():
    user_agent = [
        "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
        "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50",
        "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0",
        "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; InfoPath.3; rv:11.0) like Gecko",
        "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)",
        "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)",
        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
        "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1",
        "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11",
        "Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; TencentTraveler 4.0)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; The World)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SE 2.X MetaSr 1.0; SE 2.X MetaSr 1.0; .NET CLR 2.0.50727; SE 2.X MetaSr 1.0)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Avant Browser)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
        "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
        "Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
        "Mozilla/5.0 (iPad; U; CPU OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5",
        "Mozilla/5.0 (Linux; U; Android 2.3.7; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
        "MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
        "Opera/9.80 (Android 2.3.4; Linux; Opera Mobi/build-1107180945; U; en-GB) Presto/2.8.149 Version/11.10",
        "Mozilla/5.0 (Linux; U; Android 3.0; en-us; Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13",
        "Mozilla/5.0 (BlackBerry; U; BlackBerry 9800; en) AppleWebKit/534.1+ (KHTML, like Gecko) Version/6.0.0.337 Mobile Safari/534.1+",
        "Mozilla/5.0 (hp-tablet; Linux; hpwOS/3.0.0; U; en-US) AppleWebKit/534.6 (KHTML, like Gecko) wOSBrowser/233.70 Safari/534.6 TouchPad/1.0",
        "Mozilla/5.0 (SymbianOS/9.4; Series60/5.0 NokiaN97-1/20.0.019; Profile/MIDP-2.1 Configuration/CLDC-1.1) AppleWebKit/525 (KHTML, like Gecko) BrowserNG/7.1.18124",
        "Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0; HTC; Titan)",
        "UCWEB7.0.2.37/28/999",
        "NOKIA5700/ UCWEB7.0.2.37/28/999",
        "Openwave/ UCWEB7.0.2.37/28/999",
        "Mozilla/4.0 (compatible; MSIE 6.0; ) Opera/UCWEB7.0.2.37/28/999",
        # iPhone 6:
        "Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25",

    ]

    headers = {'User-Agent': random.choice(user_agent)}
    return headers

detail_work=Queue()


def get_urllist(url):
    html=requests.get(url=url,headers=get_user_agent(),timeout=6).content.decode('utf-8')
    tree=etree.HTML(html)
    hrefs=tree.xpath('//div[@class="deanpiclicr"]/h2/a/@href')
    # print(len(hrefs))
    print(hrefs)
    for href in hrefs:
        detail_work.put_nowait(href)




urls_work = Queue()
for i in range(1, 28):
    url = "https://www.rhino3d.asia/portal.php?mod=list&catid=1&page=%d" % i
    urls_work.put_nowait(url)


def get_url_pool():
    while not urls_work.empty():
        url = urls_work.get_nowait()
        get_urllist(url)

#获取详情页链接
def ge():
    startTime=time.time()
    tasks_list = []
    for x in range(5):
        task = gevent.spawn(get_url_pool)
        tasks_list.append(task)
    gevent.joinall(tasks_list)
    endTime = time.time()
    print('gevent用时:',endTime-startTime)

all_data=[]

def get_detail(url):
    html = requests.get(url=url, headers=get_user_agent(), timeout=6).content.decode('utf-8')
    tree = etree.HTML(html)
    title=tree.xpath('//div[@class="h hm"]/h1[@class="ph"]/text()')[0]
    print(title)
    detail=tree.xpath('//div[@class="bm vw"]')[0]
    html_detail=etree.tostring(detail,encoding='utf-8').decode()
    html_detail=html_detail.replace('src="data/','https://www.rhino3d.asia/data/')
    data=title,html_detail
    all_data.append(data)


def get_detail_pool():
    while not detail_work.empty():
        url = detail_work.get_nowait()
        get_detail(url)


#网页内容打印pdf文件
def dypdf(h1, data):
    sty = """
      <link rel="stylesheet" type="text/css" href="https://www.rhino3d.asia/template/template/dean_cgshare_161002/deancss/cssjorin/header_jr.css" />
<link href="https://www.rhino3d.asia/template/template/dean_cgshare_161002/deancss/js/main.css" type="text/css" rel="stylesheet" />
    <link href="https://www.rhino3d.asia/template/template/dean_cgshare_161002/deancss/js/a.css" type="text/css" rel="stylesheet" />
    <script src="https://www.rhino3d.asia/template/template/dean_cgshare_161002/deancss/js/jquery-1.8.3.min.js" type="text/javascript"></script>
    <script src="https://www.rhino3d.asia/template/template/dean_cgshare_161002/deancss/js/jPages.js" type="text/javascript"></script>
    <script type="text/javascript">
        var jq=jQuery.noConflict();
    </script>
    <script src="https://www.rhino3d.asia/template/template/dean_cgshare_161002/deancss/js/kefu1.js" type="text/javascript"></script>
    <script type="text/javascript">
      jq(function() {
jq("div.holder").jPages({
  containerID: "itemContainer"
});
  });
    </script>
    <script src="https://www.rhino3d.asia/template/template/dean_cgshare_161002/deancss/js/wow.min.js" type="text/javascript"></script>
<script>new WOW().init();</script>
    <script language="javascript" type="text/javascript">
        function killErrors() {
            return true;
        }
        window.onerror = killErrors;
    </script>  

    """

    datas = f'<html><head><meta charset="UTF-8">{sty}</head><body>{data}</body></html>'

    print("开始打印内容!")
    pdfkit.from_string(datas, f'{h1}.pdf', configuration=confg)
    print("打印保存成功!")


#获取详情页数据
def de():
    startTime=time.time()
    tasks_list = []
    for x in range(8):
        task = gevent.spawn(get_detail_pool)
        tasks_list.append(task)
    gevent.joinall(tasks_list)
    endTime = time.time()
    print('gevent用时:',endTime-startTime)



def main():
    ge()  # 协程
    de()
    for data in all_data:
        try:
            dypdf(data[0], data[1])
        except Exception as e:
            print("打印pdf文件出错,错误代码 {}".format(e))


if __name__=='__main__':
    main()

·················END·················

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-09-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Python与SEO学习 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档