学校网站建设流程步骤,网站建设合理性,网络营销平台推广方案,取消网站验证码引言
最近发现了一个有意思的网站#xff0c;里面充斥了大量的舔狗箴言。作为一个爬虫发烧友怎么能错过此等机会#xff0c;咱们直接就是上才艺#xff01;
类的编写
本次爬虫使用了多协程的方案进行#xff0c;保证了爬虫的速度。在这里我们新建一个爬虫类#xff0c;…引言
最近发现了一个有意思的网站里面充斥了大量的舔狗箴言。作为一个爬虫发烧友怎么能错过此等机会咱们直接就是上才艺
类的编写
本次爬虫使用了多协程的方案进行保证了爬虫的速度。在这里我们新建一个爬虫类并在里边添加上我们需要的方法。
网页的获取
首先是网页的获取部分我们在这里主要使用了多协程代码如下
# 定义多协程函数async def page_get(self):# 利用with创建协程会话async with aiohttp.ClientSession() as session:# 再次利用循环的会话来进行网页源代码的获取async with session.get(urlself.url) as resp:html await resp.text()# 调用网页解析的函数result self.page_parse(html)# 写入文件with open(tiangou.txt, modea, encodingutf-8) as f:if result \n not in f.readlines():f.write(result \n)网页解析部分
在本函数中我们调用了BeautifulSoup解析网站的内容然后返回页面的内容代码如下 def page_parse(self, html):soup BeautifulSoup(html, html.parser)result soup.find(article)return result.text类的主方法
在类的主方法中我们创建了协程循环并提交任务给协程。与此同时我们还能够根据类的属性来决定获取多少句子。 def run(self):try:loop asyncio.get_event_loop()tasks [self.page_get() for i in range(self.num)]loop.run_until_complete(asyncio.wait(tasks))except Exception as e:print(e)全部代码与运行演示
基于上述内容全部代码如下所示
import asyncio
from bs4 import BeautifulSoup
import aiohttp
from random import choiceHEADERS {user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36
}
URL https://www.nihaowua.com/dog.htmlclass crawl_dog():def __init__(self, url, headers, num100):self.url urlself.headers headersself.num numasync def page_get(self):async with aiohttp.ClientSession() as session:async with session.get(urlself.url) as resp:html await resp.text()result self.page_parse(html)with open(tiangou.txt, modea, encodingutf-8) as f:if result \n not in f.readlines():f.write(result \n)def page_parse(self, html):soup BeautifulSoup(html, html.parser)result soup.find(article)return result.textdef run(self):try:loop asyncio.get_event_loop()tasks [self.page_get() for i in range(self.num)]loop.run_until_complete(asyncio.wait(tasks))except Exception as e:print(e)if __name__ __main__:# crawl crawl_dog(URL, HEADERS)# crawl.run()with open(tiangou.txt, moder, encodingutf-8) as f:result f.readlines()print(choice(result))在主函数中新建了类并调用了run方法来进行抓取。我们随机抽几句来尝尝鲜
我不敢有什么奢望只希望亲他的时候要记得涂上我送你的唇膏…我的嘴真笨跟别人能说出花嘴巴会像开过光唯独跟你怎么说都不太对。每天都要看很多遍微博你稳居我微博经常访问第一的宝座有什么好玩的都想分享给你只为逗你一笑。你的抑郁你的不快我都看在眼里急在心头我想默默陪着你让你开心。天快亮了又一包烟抽完。你是我最孤独的心事能不能偶尔低下头看看我。问你在干嘛你问我能不能别烦你。居然询问我的意见态度真好真喜欢你
妈妈再也不同担心我没有舔狗语录喽
总结
在本文中设计并实现了抓取舔狗句子的小实例。如果你有任何问题可以私信或或者评论与我讨论。
我们下次再见