使用python的requests库编写一个使用10个线程读取domaintxt中的域名并生成随机5个字母的二级域名访问并采集页面的标题后存入resulttxt
以下是一个可能的实现:
import requests
import threading
import random
def read_domains(filename):
with open(filename) as f:
return [line.strip() for line in f]
def generate_subdomain():
letters = 'abcdefghijklmnopqrstuvwxyz'
return ''.join(random.choice(letters) for i in range(5))
def fetch_title(domain, subdomain):
url = f'http://{subdomain}.{domain}'
try:
response = requests.get(url, timeout=5)
response.raise_for_status()
title = response.text.split('<title>', 1)[1].split('</title>', 1)[0].strip()
with open('result.txt', 'a') as f:
f.write(f'{url}\t{title}\n')
except:
pass
def worker(domains):
while domains:
domain = domains.pop()
subdomain = generate_subdomain()
fetch_title(domain, subdomain)
if __name__ == '__main__':
domains = read_domains('domain.txt')
threads = [threading.Thread(target=worker, args=(domains,)) for i in range(10)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
这个程序首先定义了三个函数:
read_domains从文件中读取域名列表并返回一个列表。generate_subdomain生成一个随机的五个字母的字符串作为二级域名。fetch_title访问给定的域名和二级域名组成的URL,采集页面的标题,并将URL和标题写入result.txt。
然后,程序启动了10个线程,每个线程从域名列表中取出一个域名,生成一个随机的二级域名,调用fetch_title进行访问和采集,然后继续取下一个域名,直到所有域名都被处理完。在fetch_title中,如果访问失败或没有找到标题,则不会写入result.txt。最后,程序等待所有线程完成后退出。
原文地址: https://www.cveoy.top/t/topic/bPuF 著作权归作者所有。请勿转载和采集!