鱼C论坛

 找回密码
 立即注册
查看: 1602|回复: 2

协程获取网站标题

[复制链接]
发表于 2020-9-27 11:35:53 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. #!/isr/bin/python3
  2. #coding=utf-8

  3. import sys
  4. import argparse
  5. import threading
  6. import asyncio
  7. import re
  8. import chardet
  9. import aiohttp
  10. import ssl
  11. import csv
  12. import IPy

  13. ssl._create_default_https_context = ssl._create_unverified_context

  14. class WebTitle:

  15.     def __init__(self, urls, coroutine_count=20):
  16.         self.urls = list(set(urls))
  17.         self.coroutine_count = coroutine_count
  18.         self.result = {}

  19.     def init_queue(self):
  20.         queue = asyncio.Queue()
  21.         for url in self.urls:
  22.             queue.put_nowait(url)
  23.         return queue

  24.     def get_title_from_html(self, html):
  25.         title = 'not content!'
  26.         title_patten = r'<title>(\s*?.*?\s*?)</title>'
  27.         result = re.findall(title_patten, html)
  28.         if len(result) >= 1:
  29.             title = result[0]
  30.             title = title.strip()
  31.         return title

  32.     async def get_title(self, queue):
  33.         while True:
  34.             url = await queue.get()
  35.             print('get title for {}'.format(url))
  36.             try:
  37.                 async with aiohttp.ClientSession() as session:
  38.                     async with session.get(url, timeout=3, ssl=ssl.SSLContext()) as resp:
  39.                         html = await resp.text()
  40.                 title = self.get_title_from_html(html)
  41.                 print('{}:{}'.format(url,title))
  42.                 self.result[url] = title
  43.             except Exception as e:
  44.                 print('{} has error: {} '.format(url,str(e)))               
  45.             queue.task_done()

  46.     async def start_task(self):
  47.         queue = self.init_queue()
  48.         tasks = []
  49.         for i in range(self.coroutine_count):
  50.             task = asyncio.create_task(self.get_title(queue))
  51.             tasks.append(task)

  52.         await queue.join()

  53.         for task in tasks:
  54.             task.cancel()

  55.         await asyncio.gather(*tasks, return_exceptions=True)


  56.     def start(self):
  57.         asyncio.run(self.start_task())

  58.     def write_result(self, outfile):
  59.         urls = self.result.keys()
  60.         with open(outfile, 'w') as f:
  61.             writer = csv.writer(f)
  62.             writer.writerow(['url','title'])
  63.             for url in urls:
  64.                 title = self.result[url]
  65.                 writer.writerow([url, title])
  66.         with open(outfile + '_alive.txt', 'w') as f:
  67.             for url in urls:
  68.                 f.write(url + '\n')
  69.         
  70.         print('alive urls write to {}'.format(outfile + '_alive.txt'))
  71.         print('title write to {}'.format(outfile))

  72. def parse_args():
  73.     parser = argparse.ArgumentParser(description='A tool that can get title for domains or urls')
  74.     parser.add_argument('-d','--domain', metavar='domain.txt', dest='domain_file', type=str, help=u'domain to get title')
  75.     parser.add_argument('-u','--url', metavar='url.txt', dest='url_file', type=str, help=u'urls to get title')
  76.     parser.add_argument('-i','--ip', metavar='ip.txt', dest='ip_file', type=str, help=u'ips to get title')
  77.     parser.add_argument('-t','--coroutine', metavar='20', dest='coroutine_count', type=int, default=20,help=u'coroutines to get title')
  78.     parser.add_argument('-o','--outfile', metavar='result.txt', dest='outfile', type=str, default='result.csv',help=u'file to result')
  79.     args = parser.parse_args()
  80.     if args.url_file == None and args.domain_file == None and args.ip_file == None:
  81.         parser.print_help()
  82.         sys.exit()
  83.     return args


  84. def main():
  85.     try:
  86.         args = parse_args()
  87.         urls = []

  88.         if args.domain_file:
  89.             with open(args.domain_file) as f:
  90.                 domains = f.readlines()
  91.             for domain in domains:
  92.                 domain = domain.strip()
  93.                 if domain != '':
  94.                     urls.append('http://' + domain)
  95.                     urls.append('https://' + domain)

  96.         if args.url_file:
  97.             with open(args.url_file) as f:
  98.                 urls2 = f.readlines()
  99.             for url in urls2:
  100.                 url = url.strip()
  101.                 if url != '':
  102.                     urls.append(url)

  103.         if args.ip_file:
  104.             with open(args.ip_file) as f:
  105.                 ips = f.readlines()
  106.             for ip in ips:
  107.                 ip = ip.strip()
  108.                 if ip != '':
  109.                     # cidr_ip = IPy.IP(ip)
  110.                     cidr_ip = IPy.IP(ip, make_net=1)
  111.                     for i in cidr_ip:
  112.                         urls.append('http://' + str(i))
  113.                         urls.append('https://' + str(i))

  114.         web_title = WebTitle(urls, args.coroutine_count)
  115.         web_title.start()
  116.         web_title.write_result(args.outfile)
  117.     except Exception as e:
  118.         print(e)

  119. def banner():
  120.     print('''==================''')


  121. if __name__ == '__main__':
  122.     banner()
  123.     main()

复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2020-9-27 11:37:27 | 显示全部楼层
这个目的是用域名 网址 IP 任意一个信息,或者全部信息,获取网站标题,但现在只能实现IP爬取网站标题,域名 网址实现不了。建议在终端命令执行,安装aiohttp IPy chardet
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-9-27 11:38:42 | 显示全部楼层
希望大哥们看看,这个域名和网址的功能获取网站标题,怎么修改
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-27 17:40

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表