Python3--爬取海词信息
上代码:
#!/usr/bin/python3import queue
import threading
import requests,csv,time,random
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
import pandas as pd exitFlag = 0#利用pandas读取csv文件
def getNames(csvfile):data = pd.read_csv(csvfile,delimiter='|') # 1--读取的文件编码问题有待考虑names = data['EnName']return names#获取ip列表
def get_ip_list(): f=open('ip.txt','r') ip_list=f.readlines() f.close() return ip_list #从IP列表中获取随机IP
def get_random_ip(ip_list): proxy_ip = random.choice(ip_list) proxy_ip=proxy_ip.strip('\n') proxies = {'https': proxy_ip} return proxies #功能:将信息写入文件
def write_file(filePath,row): with open(filePath,'a+',encoding='utf-8',newline='') as csvfile: spanreader = csv.writer(csvfile,delimiter='|',quoting=csv.QUOTE_MINIMAL) spanreader.writerow(row) def get_content(url,ip_list):try:try:time.sleep(1)proxies = get_random_ip(ip_list)headers = {'User-Agent':str(UserAgent().random)}req = requests.get(url=url, proxies=proxies,headers=headers,timeout=20)except:print("重新运行")time.sleep(10)proxies = get_random_ip(ip_list)headers = {'User-Agent':str(UserAgent().random)}req = requests.get(url=url, proxies=proxies,headers=headers,timeout=40)except:print("第二次重新运行")time.sleep(15)proxies = get_random_ip(ip_list)headers = {'User-Agent':str(UserAgent().random)}req = requests.get(url=url, proxies=proxies,headers=headers)req.encoding = 'utf-8'soup = BeautifulSoup(req.text,'lxml')content = soup.find_all('div',class_='mbox')return req.status_code, content#获取准确的英文名、中文名、名字含义、来源、性别等信息
def get_infor_header(content):content = content.find_all('span')EnName = []CnName = []Gender = []Source = []Meaning = []EnName.append(content[0].get_text())if len(content) != 1:CnName.append(content[1].get_text())Meaning.append(content[2].get_text()) Source.append(content[3].get_text())Gender.append(content[4].em.get('title'))else:CnName.append('')Meaning.append('') Source.append('')Gender.append('')#信息的链接方式EnName|CnName|Gender|Source|Meaninglist_header = EnName + CnName + Gender + Source + Meaningreturn list_header#获取英文名对应的名人
def get_infor_celebrity(content):content = content.find_all('li')list_celebrity = []str_celebrity=''for each in content:if not str_celebrity:str_celebrity +=each.get_text()else:str_celebrity +='@' + each.get_text()list_celebrity.append(str_celebrity)return list_celebrityclass myThread (threading.Thread):def __init__(self, threadID, name, q,ip_list):threading.Thread.__init__(self)self.threadID = threadIDself.name = nameself.q = qself.ip_list = ip_listdef run(self):print ("开启线程:" + self.name)process_data(self.name, self.q,ip_list)print ("退出线程:" + self.name)def process_data(threadName, q,ip_list):while not exitFlag:queueLock.acquire()if not workQueue.empty():data = q.get()queueLock.release()print ("%s processing %s" % (threadName, data))url = 'http://ename.dict.cn/{}'.format(data)status_code, content = get_content(url,ip_list)if status_code==200:#获取准确的中文名、名字含义、来源、性别等信息list_header = get_infor_header(content[0])#获取名人信息list_celebrity = get_infor_celebrity(content[1])row = list_header + list_celebrityqueueLock.acquire()write_file('haici_infor.csv',row)queueLock.release()else:queueLock.release()time.sleep(1)threadList = ["Thread-1", "Thread-2", "Thread-3", "Thread-4", "Thread-5", "Thread-6", "Thread-7", "Thread-8", "Thread-9", "Thread-10"]
nameList = getNames('A-Z.csv')
queueLock = threading.Lock()
workQueue = queue.Queue(100000)
threads = []
threadID = 1# 创建新线程
ip_list = get_ip_list()
for tName in threadList:thread = myThread(threadID, tName, workQueue,ip_list)thread.start()threads.append(thread)threadID += 1# 填充队列
queueLock.acquire()
for word in nameList:workQueue.put(word)
queueLock.release()# 等待队列清空
while not workQueue.empty():pass# 通知线程是时候退出
exitFlag = 1# 等待所有线程完成
for t in threads:t.join()
print ("退出主线程")
Python3--爬取海词信息相关推荐
- Beautiful爬取海词网词汇意思和短语
Beautiful爬取海词网词汇意思和短语 直接上代码 # -*- encoding:utf-8 -*- import urllib.request # 导入urllib库的request模块 fro ...
- Python3 爬取豆瓣电影信息
原文链接: Python3 爬取豆瓣电影信息 上一篇: python3 爬取电影信息 下一篇: neo4j 查询 豆瓣api https://developers.douban.com/wiki/?t ...
- python3爬取豆瓣电影信息,图片,有源码(使用简单)
首先下载安装python3安装教程 在控制台(Windows按 win+R)下载python插件: python -m pip install --upgrade pip # 更新 pip insta ...
- python3爬取微信通讯录信息并保存头像
安装 pip3 install itchat 代码 # -*- coding: utf-8 -*- import itchat#用于二维码登录微信, itchat.auto_login() #获取通讯 ...
- Python爬取12306车票信息
Python3爬取12306车票信息 第一次写爬虫,咱从入门级--12306车票爬取 开始 我们要爬取的信息是https://www.12306.cn/index/上的车票信息 当我们选择出发地和目的 ...
- Python3 爬取携程网[2]: 爬取北京五星级酒店详细信息
目录 1. 需求分析 2. 实验环境 3. 具体实现 3.1 分析页面 3.2 请求 3.3 响应 3.3.1 BeautifulSoup提取标签信息 3.3.2 正则表达式提取字符串信息 3.3.3 ...
- Python2 Python3 爬取赶集网租房信息,带源码分析
*之前偶然看了某个腾讯公开课的视频,写的爬取赶集网的租房信息,这几天突然想起来,于是自己分析了一下赶集网的信息,然后自己写了一遍,写完又用用Python3重写了一遍.之中也遇见了少许的坑.记一下.算是 ...
- Python3爬取网页信息乱码怎么解决?(更新:已解决)
更新:乱码问题已经解决了. 将下面代码中的红色部分改为下面这样就不会出现个别职位信息乱码的情况了. soup2 = BeautifulSoup(wbdata2, 'html.parser',from_ ...
- Selenium+Python3爬取微博我发出的评论信息
Selenium+Python3爬取微博我发出的评论信息 需求 代码 注: 需求 记录对话信息:对话文本.时间.用户.被回复链接.被回复用户.被回复文本. 将数据信息持久化保存,可选择截图. 代码 # ...
最新文章
- 秋招要跪?不怕!领走这份机器学习求职攻略
- Maven 模块继承、聚合
- 010_CSS后代选择器
- python系统字体_Python matplotlib修改默认字体的操作
- linux存储pdf伟岸_Linux 文件恢复的原理
- 出人意料的生日会400字_出人意料的有效遗传方法进行特征选择
- [数据库] --- clickhouse
- 《Unix/linux编程实践教程》------重定向程序的I/O
- mac docker nginx 配置
- springMVC入门二
- Atitit prgrmlan topic--express lan QL query lan表达式语言 目录 1. 通用表达语言(CEL)	1 1.1. 8.2 功能概述	1 1.2. Ongl
- 【优化算法】社会群体优化算法(SGO)【含Matlab源码 1449期】
- 详解MATLAB/Simulink通信系统建模与仿真源码
- PRML 1.5 决策论
- 手机版python3.8.1下载_python3.8.1汉化版
- JavaScript 身份证验证
- 【友盟+】营销大数据论坛完美收官:数据驱动营销智能
- 简单的w7-->w10的方法
- 【JS】使用jQuery制作图片手风琴效果
- Linux-CentOS上的服务搭建
热门文章
- SSL/TLS握手过程
- oracle 枚举_枚举导出为sql语句java实现
- 机械师怎么打开计算机管理,机械师创物者-R笔记本智能控制中心使用教程
- python 拼音姓名排序_Python一秒将全部中文姓名转为拼音!
- Qt中的QColorDialog
- 三星手机Android9和10的区别,三星开始在Galaxy Note 9上测试Android 10
- 关系到了冰点_疫情下半场,如何修复跌至冰点的亲子关系,让自己和家人活出幸福感?...
- python当中pip使用_python
- php删除多表数据,mysql – 从多个表中删除数据
- otc机器人氩弧焊机_轻松搞定砂光机前后连线翻转!【富全智能】全自动180度圆筒式翻板机...