您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
如何使用python多线程爬取数据?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
首先找到所有的tr标签,与class="odd"的标签,然后提取出来。
然后再依次找到tr标签里面的所有td标签,然后只提取出里面的[1,2,5,9]这四个标签的位置,其他的不提取。
最后可以写出提取单一页面的代码,提取后将其保存到文件中。
import sys,re,threading import requests,lxml from queue import Queue import argparse from bs4 import BeautifulSoup head = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36"} if __name__ == "__main__": ip_list=[] fp = open("SpiderAddr.json","a+",encoding="utf-8") url = "https://www.blib.cn/url/xcdl.html" request = requests.get(url=url,headers=head) soup = BeautifulSoup(request.content,"lxml") data = soup.find_all(name="tr",attrs={"class": re.compile("|[^odd]")}) for item in data: soup_proxy = BeautifulSoup(str(item),"lxml") proxy_list = soup_proxy.find_all(name="td") for i in [1,2,5,9]: ip_list.append(proxy_list[i].string) print("[+] 爬行列表: {} 已转存".format(ip_list)) fp.write(str(ip_list) + '\n') ip_list.clear()
爬取后会将文件保存为 SpiderAddr.json 格式。
最后再使用另一段代码,将其转换为一个SSR代理工具直接能识别的格式,{'http': 'http://119.101.112.31:9999'}
import sys,re,threading import requests,lxml from queue import Queue import argparse from bs4 import BeautifulSoup if __name__ == "__main__": result = [] fp = open("SpiderAddr.json","r") data = fp.readlines() for item in data: dic = {} read_line = eval(item.replace("\n","")) Protocol = read_line[2].lower() if Protocol == "http": dic[Protocol] = "http://" + read_line[0] + ":" + read_line[1] else: dic[Protocol] = "https://" + read_line[0] + ":" + read_line[1] result.append(dic) print(result)
完整多线程版代码如下所示。
import sys,re,threading import requests,lxml from queue import Queue import argparse from bs4 import BeautifulSoup head = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36"} class AgentSpider(threading.Thread): def __init__(self,queue): threading.Thread.__init__(self) self._queue = queue def run(self): ip_list=[] fp = open("SpiderAddr.json","a+",encoding="utf-8") while not self._queue.empty(): url = self._queue.get() try: request = requests.get(url=url,headers=head) soup = BeautifulSoup(request.content,"lxml") data = soup.find_all(name="tr",attrs={"class": re.compile("|[^odd]")}) for item in data: soup_proxy = BeautifulSoup(str(item),"lxml") proxy_list = soup_proxy.find_all(name="td") for i in [1,2,5,9]: ip_list.append(proxy_list[i].string) print("[+] 爬行列表: {} 已转存".format(ip_list)) fp.write(str(ip_list) + '\n') ip_list.clear() except Exception: pass def StartThread(count): queue = Queue() threads = [] for item in range(1,int(count)+1): url = "https://www.xicidaili.com/nn/{}".format(item) queue.put(url) print("[+] 生成爬行链接 {}".format(url)) for item in range(count): threads.append(AgentSpider(queue)) for t in threads: t.start() for t in threads: t.join() # 转换函数 def ConversionAgentIP(FileName): result = [] fp = open(FileName,"r") data = fp.readlines() for item in data: dic = {} read_line = eval(item.replace("\n","")) Protocol = read_line[2].lower() if Protocol == "http": dic[Protocol] = "http://" + read_line[0] + ":" + read_line[1] else: dic[Protocol] = "https://" + read_line[0] + ":" + read_line[1] result.append(dic) return result if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-p","--page",dest="page",help="指定爬行多少页") parser.add_argument("-f","--file",dest="file",help="将爬取到的结果转化为代理格式 SpiderAddr.json") args = parser.parse_args() if args.page: StartThread(int(args.page)) elif args.file: dic = ConversionAgentIP(args.file) for item in dic: print(item) else: parser.print_help()
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。