本文实例为大家分享了python爬取微信公众号文章的具体代码,供大家参考,具体内容如下
# -*- coding: utf-8 -*- import requests from bs4 import BeautifulSoup from requests.exceptions import RequestException import time import random import MySQLdb import threading import socket import math socket.setdefaulttimeout(60)#这里对整个socket层设置超时时间。后续文件中如果再使用到socket,不必再设置 glock = threading.Lock() #定义全局锁 CATEGORY_URL= ['http://www.we123.com/gzh/onclick/'] #获取地区分类链接 all_url = [] # ALL_URLS = [] #所有详细页面链接 proxy_list = [] #IP池 URL = 'http://www.we123.com' PAGE_URL = [] #所有分页链接 #获取Ip池 def get_ip(): headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'} url = 'http://http-webapi.zhimaruanjian.com'#可以使用芝麻代理,好用稳定还不贵 resp = requests.get(url,headers=headers) obj = resp.json() #获取json ip池对象 for ip in obj: arr = 'http://' + str(ip['ip']) + ':' + str(ip['port']) proxy_list.append(arr) #获取页面源码函数 def get_html(url): # headers = {} user_agent_list = [ 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.3538.400 QQBrowser/9.6.12501.400', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0' ] # user_agent = random.choice(user_agent_list) headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.3538.400 QQBrowser/9.6.12501.400' } # 代理,免费的代理只能维持一会可能就没用了,自行更换 # proxy_list = [ # "http://27.192.185.62:3252", # ] # proxy_ip = random.choice(proxy_list) # proxies = {'http': proxy_ip} # print(str(url)) try: resp = requests.get(url,headers=headers) # print("72行:status_code = " + str(resp.status_code)) # print(type(resp.text)) # print(resp.url) # 请求的url if resp.status_code == 200: return resp elif resp.status_code == 404: return resp elif resp.status_code == 500: return resp return resp except RuntimeError: print("超时") return "error" except ConnectionError: print("连接超时") return "error" except RequestException: print("http请求父类错误") with open('url_exception.txt','a+', encoding='utf-8') as f: f.write(str(url)) f.write('\n') return "error" #获取区域分类链接 def get_categoty_url(): url = 'http://www.we123.com/gzh/onclick/' resp = get_html(url) soup = BeautifulSoup(resp.text,'lxml') html = soup.select('div.div-subs2 > div.divst-content > div.divst-subs > li > a') # 获取区域分类链接 for i in html: city = i['href'].split("/")[-1] if (city == '海外' or city == '台湾' or city == '澳门'): continue url = URL + i['href'] CATEGORY_URL.append(url) print(CATEGORY_URL) #获取每个区域下所有分页链接 def get_page_url(url): city = url.split('/')[-1] html = get_html(url) if html == "error": print("98行:connect url error") time.sleep(random.randint(10,20)) return "error" soup = BeautifulSoup(html.text,'lxml') #获取总条数 all_nums = soup.select("div.page > a > b") if len(all_nums) == 0: return "error" else: all_nums = soup.select("div.page > a > b")[0].get_text() #获取总分页数 all_pages = math.ceil((int(all_nums) / 30)) #获取所有分页链接 all_page_url = [] for i in range(0,int(all_pages)): page_url = 'http://www.we123.com/e/action/ListInfo.php"error": print("141行:connect url error") time.sleep(2) return soup = BeautifulSoup(html.text,'lxml') info_urls = soup.select('div.gzhRight > div.gzh_list > ul > li > a') for x in info_urls: i_url = URL + x['href'] ALL_URLS.append(i_url) print("库存链接共:" + str(len(ALL_URLS))) glock.release() #解锁 #获取每一页需要的数据 def get_data(): while True: global ALL_URLS #设置全局变量 glock.acquire() #加锁 print("当前库存:"+str(len(ALL_URLS))) if len(ALL_URLS) == 0: glock.release() #解锁 print('159 行 :ALL_URLS 为空') break else: url = ALL_URLS.pop() print("开始抓取数据:" + url) glock.release() #解锁 time.sleep(1) #睡眠1秒钟 html = get_html(url) if html == "error": print("168行:connect url error") time.sleep(random.randint(2, 4)) return html.encoding='utf-8' #显式地指定网页编码,一般情况可以不用 soup = BeautifulSoup(html.text,'lxml') #公众号名称 names = soup.select('div.artcleLeft > div.xcxnry > div.xcxtop > div.xcxtop_left > div.gzhtop_logo > h1') #微信号id accounts = [] accounts.append(soup.select('div.artcleLeft > div.xcxnry > div.xcxtop > div.xcxtop_left > div.gzhtop_logo > p')[0]) #微信头像 imgs = soup.select('div.artcleLeft > div.xcxnry > div.xcxtop > div.xcxtop_left > div.gzhtop_logo > img') #公众号二维码 QR_codes= soup.select('div.artcleLeft > div.xcxnry > div.xcxtop > div.xcxtop_right > img') #介绍 descs = soup.select('div.artcleLeft > div.xcxnry > div.xcxinfo') #公众号分类 categorys = [] category = '' cate = soup.select('div.artcleLeft > div.xcxnry > div.xcxtop > div.xcxtop_left > div.xcx_p > span > a') if not len(cate) == 0: category = cate[0].get_text() else: category = '综合' glock.acquire() #加锁 for name,account,img,QR_code,desc in zip(names,accounts,imgs,QR_codes,descs): data = { 'name':name.get_text(), 'category':category, 'account':account.get_text().split(":")[-1], 'img':img['src'], 'QR_code':QR_code['src'], 'desc':desc.get_text() } add_data(data,url) glock.release() #解锁 #添加数据 def add_data(data,url): con = MySQLdb.connect('127.0.0.1','root','root','test',charset="utf8",use_unicode=True) cursor = con.cursor() # exit() insert_sql = """ insert ignore into weixin5(w_name,category,account,img,QR_code,introduce) VALUES (%s,%s,%s,%s,%s,%s) """ print('212行 :' + data['name'] + '_' + data['account'] + '添加成功!-' + url) try: cursor.execute(insert_sql,(data['name'],data['category'],data['account'],data['img'],data['QR_code'],str(data['desc']))) con.commit() except: ALL_URLS.insert(0,url) print("218行:" + URL + '插入失败') con.rollback() con.close() # 将时间字符串转化为时间戳 def time_to(dt): timeArray = time.strptime(dt, "%Y年%m月%d日") timestamp = int(time.mktime(timeArray)) return timestamp #启动多线程爬取 def main(): for x in range(3): th = threading.Thread(target=get_info_urls) th.start() # get_info_urls() time.sleep(3) for x in range(5): th = threading.Thread(target=get_data) th.start() if __name__ == '__main__': # 计时 t1 = time.time() # 调用函数 get_ip() #获取ip池 get_page_urls() time.sleep(2) # get_categoty_url() main() print(time.time() - t1)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
暂无“python爬取微信公众号文章”评论...
稳了!魔兽国服回归的3条重磅消息!官宣时间再确认!
昨天有一位朋友在大神群里分享,自己亚服账号被封号之后居然弹出了国服的封号信息对话框。
这里面让他访问的是一个国服的战网网址,com.cn和后面的zh都非常明白地表明这就是国服战网。
而他在复制这个网址并且进行登录之后,确实是网易的网址,也就是我们熟悉的停服之后国服发布的暴雪游戏产品运营到期开放退款的说明。这是一件比较奇怪的事情,因为以前都没有出现这样的情况,现在突然提示跳转到国服战网的网址,是不是说明了简体中文客户端已经开始进行更新了呢?
更新动态
2024年11月26日
2024年11月26日
- 凤飞飞《我们的主题曲》飞跃制作[正版原抓WAV+CUE]
- 刘嘉亮《亮情歌2》[WAV+CUE][1G]
- 红馆40·谭咏麟《歌者恋歌浓情30年演唱会》3CD[低速原抓WAV+CUE][1.8G]
- 刘纬武《睡眠宝宝竖琴童谣 吉卜力工作室 白噪音安抚》[320K/MP3][193.25MB]
- 【轻音乐】曼托凡尼乐团《精选辑》2CD.1998[FLAC+CUE整轨]
- 邝美云《心中有爱》1989年香港DMIJP版1MTO东芝首版[WAV+CUE]
- 群星《情叹-发烧女声DSD》天籁女声发烧碟[WAV+CUE]
- 刘纬武《睡眠宝宝竖琴童谣 吉卜力工作室 白噪音安抚》[FLAC/分轨][748.03MB]
- 理想混蛋《Origin Sessions》[320K/MP3][37.47MB]
- 公馆青少年《我其实一点都不酷》[320K/MP3][78.78MB]
- 群星《情叹-发烧男声DSD》最值得珍藏的完美男声[WAV+CUE]
- 群星《国韵飘香·贵妃醉酒HQCD黑胶王》2CD[WAV]
- 卫兰《DAUGHTER》【低速原抓WAV+CUE】
- 公馆青少年《我其实一点都不酷》[FLAC/分轨][398.22MB]
- ZWEI《迟暮的花 (Explicit)》[320K/MP3][57.16MB]