Python多线程爬取行行网电子书

行行网电子书多线程爬取-撸代码

代码非常简单,有咱们前面的教程做铺垫,很少的代码就可以实现完整的功能了,最后把采集到的内容写到 csv 文件里面,(csv 是啥,你百度一下就知道了) 这段代码是IO密集操作 我们采用aiohttp模块编写。

第1步

拼接URL,开启线程。

import requests

# 导入协程模块
import asyncio
import aiohttp
'''
遇到不懂的问题?Python学习交流群:821460695满足你的需求,资料都已经上传群文件,可以自行下载!
'''

headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
           "Host": "www.ireadweek.com",
           "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"}

async def get_content(url):
    print("正在操作:{}".format(url))
    # 创建一个session 去获取数据 
    async with aiohttp.ClientSession() as session:
        async with session.get(url,headers=headers,timeout=3) as res:
            if res.status == 200:
                source = await res.text()  # 等待获取文本
                print(source)


if __name__ == '__main__':
    url_format = "http://www.ireadweek.com/index.php/bookInfo/{}.html"
    full_urllist = [url_format.format(i) for i in range(1,11394)]  # 11394
    loop = asyncio.get_event_loop()
    tasks = [get_content(url) for url in full_urllist]
    results = loop.run_until_complete(asyncio.wait(tasks))

上面的代码可以同步开启N多个线程,但是这样子很容易造成别人的服务器瘫痪,所以,我们必须要限制一下并发次数,下面的代码,你自己尝试放到指定的位置吧。

sema = asyncio.Semaphore(5)
# 为避免爬虫一次性请求次数太多,控制一下
async def x_get_source(url):
    with(await sema):
        await get_content(url)

第2步

处理抓取到的网页源码,提取我们想要的元素,我新增了一个方法,采用lxml进行数据提取。

def async_content(tree):
    title = tree.xpath("//div[@class='hanghang-za-title']")[0].text
    # 如果页面没有信息,直接返回即可
    if title == '':
        return
    else:
        try:
            description = tree.xpath("//div[@class='hanghang-shu-content-font']")
            author = description[0].xpath("p[1]/text()")[0].replace("作者:","") if description[0].xpath("p[1]/text()")[0] is not None else None
            cate = description[0].xpath("p[2]/text()")[0].replace("分类:","") if description[0].xpath("p[2]/text()")[0] is not None else None
            douban = description[0].xpath("p[3]/text()")[0].replace("豆瓣评分:","") if description[0].xpath("p[3]/text()")[0] is not None else None
            # 这部分内容不明确,不做记录
            #des = description[0].xpath("p[5]/text()")[0] if description[0].xpath("p[5]/text()")[0] is not None else None
            download = tree.xpath("//a[@class='downloads']")
        except Exception as e:
            print(title)
            return

    ls = [
        title,author,cate,douban,download[0].get('href')
    ]
    return ls

第3步

数据格式化之后,保存到csv文件,收工!

 print(data)
 with open('hang.csv', 'a+', encoding='utf-8') as fw:
     writer = csv.writer(fw)
     writer.writerow(data)
 print("插入成功!")

行行网电子书多线程爬取-运行代码,查看结果

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值