当前位置:   article > 正文

python3实现微信公众号文章爬取_python解析微信公众号文章的文本

python解析微信公众号文章的文本

基于搜狗微信的文章爬取

前言:文章仅用于学习交流,不足之处欢迎小伙伴指正!

一、功能介绍:

已实现功能:

1、爬取搜狗微信上的分类一栏的所有事件及其他的所有标题事件和加载更多,返回文章链接与标题,并存入数据库中,后续可直接根据链接下载文章。

2、根据输入内容定向爬取文章,返回链接与标题。

待实现功能:

1、根据数据库中的链接爬取公众号的所有相关文章,保存于数据库,并对所有文章分类存档。

2、实现UI界面(PyQt5),根据需要对程序打包为可执行文件。

二、运用到的知识点介绍:

selenisum(实现简单的搜狗微信主页源码获取)

代理池原理  (给定ip源,简单的判断ip是否可用)

线程池原理    (实现多线程爬取,增加爬取效率)

oo面向思想     (面向对象编程,分模块编程,增加可读性,方便后期维护)

一些常用的库    (os、time、random、requests、pymysql、queue、threading)

三、文件的结构组成及功能说明

1、main.py:该文件为程序的入口,即启动文件,功能:几个模块之间的数据传输的中转站。

2、ip_pool.py:  该文件是ip代理池文件, 功能:将给定的ip列表进行筛选,选出可用的ip方便后续请求。

2、spider_page.py:  该文件用于提取网页源码, 功能:selenisum去获取主页源码。

3、settings.py:该文件为配置文件, 功能:我们在程序启动之前可以选择爬虫的爬取方向,当然这个方向是由自己给定的。

4、is_API_Run.py:  该文件是API执行文件,功能:根据settings文件的配置输入,从而决定执行那些API函数。

5、API_Function.py:  该文件是API文件,功能:实现了各个API函数的功能实现。

6、thread_pool.py:该文件为线程池文件,功能:实现了从数据库中获取链接,去多线程的下载文章。

四、程序运行步骤代码解读

1、在我们开始之前,让我们先了解下搜狗微信的主页面:https://weixin.sogou.com/      若已了解则跳过这一步。

2、文章这里以主页中的 “搜索热词”、“编辑精选”、“热点文章”、“热门”举例演示。

3、从main文件的程序入口启动程序,首先该文件导入了一些包和编写的其他模块文件,并编写了相应的两个函数,分别是panding()函数、ip()函数,对应功能见代码注释,其他的一些模块文件在后边会有解释

文件名:main.py

  1. '''
  2. 启动程序
  3. '''
  4. #导包和导入自定义模块文件
  5. #自己编写的模块文件
  6. from spider_page import __init__source
  7. from is_API_Run import read_settings_run_func
  8. from thread_pool import Open_Thread_Assign_Links
  9. from ip_pool import ip_Pool
  10. #python包
  11. import os
  12. import time
  13. import random
  14. def ip(IP_POOL):
  15. '''
  16. 从IP_POOL(ip池)随机选出一个ip将其返回给主程序使用,
  17. :param IP_POOL: IP池
  18. :return: proxies ------随机的一个代理ip
  19. '''
  20. proxies = {
  21. "http": random.choice(IP_POOL),
  22. }
  23. return proxies
  24. def panding(proxies):
  25. '''在此处实现:判断工作文件路径下的page_source目录下是否有名为当日的文件(20210511.txt)--年月日的txt文件,
  26. 判断文件名是否符合要求(一天之内生成的) 若有则读取出来赋值page,返回给主程序使用,若没有则执行page=__init__source().html_source语句。
  27. 获取网页源代码,再将其命名保存,并且返回给主程序使用'''
  28. work_path = os.getcwd() # 获取工作路径
  29. html_path = os.path.join(work_path, 'page_source')
  30. if len(os.listdir(html_path)) > 0: # 判断路径下是否有文件
  31. flag = False
  32. for x in os.listdir(html_path): # 罗列出路径下所有的文件
  33. print("x:", x)
  34. if x == (time.strftime(r'%Y%m%d') + r'.txt'): # 找出当天生成的文件
  35. print("x:", x)
  36. with open(os.path.join(html_path, x), 'r', encoding="utf-8") as f:
  37. page = f.read()
  38. return page
  39. # 没有当天的文件就创建文件并写入html源码
  40. page = __init__source(proxies).html_source
  41. with open(os.path.join(html_path, time.strftime(r'%Y%m%d') + r'.txt'), 'w', encoding="utf-8") as f:
  42. f.write(page)
  43. else:
  44. page = __init__source(proxies).html_source
  45. with open(os.path.join(html_path, time.strftime(r'%Y%m%d') + r'.txt'), 'w', encoding="utf-8") as f:
  46. f.write(page)
  47. return page #将源码返回给主程序使用
  48. if __name__ == '__main__':
  49. IP_POOL = ip_Pool() # 启动ip代理池 (初始化ip类,并生成代理池对象,接下来从对象中获取ip池---IP_POOL.ip_pool)
  50. proxies = ip(IP_POOL.ip_pool) # 随机从ip池中拿出一个代理ip---proxies
  51. page = panding(proxies) # 初始化源码 (用代理ip请求主页源码,并保存于程序工作目录下的page_source文件夹下的以年月日为名的txt文件。)
  52. read_settings_run_func(page, proxies) # 读取配置文件并执行相应的API函数。
  53. Open_Thread_Assign_Links(proxies) # 开启线程池下载公众号文章

4、然后解释一下ip代理池这个模块文件,该文件实现了动态的从网上的ip源获取可用ip,并初始化IP代理池为5个ip,然后会在主程序运行过程中一直对ip池中的ip进行可用性验证,若ip过期不可用,那将该ip从ip代理池中删除,再从ip源获取可用ip补充ip代理池。具体功能实现见代码。该文件模块可以拿出来单独使用,并不局限于单独的某个程序。单独使用方法,后面会有具体说明。

文件名:ip_pool.py

  1. # 导包
  2. import requests
  3. import time
  4. import re
  5. import threading
  6. # 定义测试的url链接,这里暂且选用www.baidu.com
  7. url = 'https://www.baidu.com/'
  8. # 定义测试的url链接www.baidu.com的请求头。
  9. headers = {
  10. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
  11. 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'max-age=0',
  12. 'Connection': 'keep-alive',
  13. 'Cookie': 'BIDUPSID=EAAEC44F956EC0051F3EB986A600267F; PSTM=1618841564; BD_UPN=12314753; __yjs_duid=1_fc17df5ce48c903e96c35412849fa9c21618841573172; BDUSS=F2Yn5VfmNzMFkwNjE3TzNKY0V3UVJUUW0wOUFDTVVEdU82cG9Id1lmSzEwSzFnSUFBQUFBJCQAAAAAAAAAAAEAAADrnKS8vsXOsr3wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALVDhmC1Q4ZgY0; BDUSS_BFESS=F2Yn5VfmNzMFkwNjE3TzNKY0V3UVJUUW0wOUFDTVVEdU82cG9Id1lmSzEwSzFnSUFBQUFBJCQAAAAAAAAAAAEAAADrnKS8vsXOsr3wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALVDhmC1Q4ZgY0; BAIDUID=FAD97B32882628A65DB481B25993EEA8',
  14. 'Host': 'www.baidu.com', 'Referer': 'https', 'Sec-Fetch-Dest': 'document', 'Sec-Fetch-Mode': 'navigate',
  15. 'Sec-Fetch-Site': 'cross-site', 'Sec-Fetch-User': '?1', 'Upgrade-Insecure-Requests': '1',
  16. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36 SLBrowser/7.0.0.4071 SLBChan/15'}
  17. # 对url网站发起请求,根据返回体的状态码判断是否请求成功,若成功则该ip可用,若不成功则ip不可用,将ip从ip池中移除。
  18. # 那么这个ip池要保证在整个程序运行用ip皆可用
  19. # ip供应源(ip_source)
  20. ip_source = 'ip源'
  21. # 初始化ip池为空(Ip_Pool)
  22. Ip_Pool = []
  23. # ip的预期存留时间M
  24. M = 0
  25. # ip代理池类
  26. class ip_Pool:
  27. def __init__(self, ):
  28. self.ip_pool = [] # 初始化ip池属性,方便后续的ip池赋值。
  29. threading.Thread(target=self.return_ip_pool).start() # 开启子线程动态处理ip代理池,目的:保证ip池中ip的可用性的同时,又不会影响其他程序运行。所以开辟一个子线程。
  30. time.sleep(6) # 加这个等待时间,目的:给子线程足够的时间去获取ip,并填充ip池,保证返回给主程序的ip池不为空。
  31. def ip_yield(self):
  32. while True:
  33. while len(Ip_Pool) < 5: # 这里的while循环语句 目的:用于检测ip池中是否始终满足个数要求
  34. ip = requests.get(ip_source).text # 从ip源获取ip文本。
  35. if '{' in ip: # 检测从ip源是否成功获取到ip。若未获取到ip则会返回一个包含字典样式的字符串。
  36. continue
  37. # time.sleep(0.5) # 可以增加等待时间,以提高获取到ip的成功率
  38. else:
  39. ip = re.match('\S*', ip).group() # 对获取到的ip文本简单处理,目的去除\r\n字符。
  40. Ip_Pool.append(ip) # 将ip添加到ip池中。
  41. # 暂停M分钟,并将Ip_Pool返回出去使用
  42. yield Ip_Pool
  43. time.sleep(M)
  44. print('将IP池返回给主程序使用------' + str(M) + '半分钟后对IP池进行检测是否可用--------')
  45. #以下for循环是用于检测ip池中ip是否过期。
  46. for x in Ip_Pool:
  47. proxies = {'http': x}
  48. try:
  49. if requests.get(url, proxies=proxies, headers=headers).status_code == 200:
  50. # print('该ip正常,还能继续使用半分钟')
  51. pass
  52. except Exception:
  53. print('存在一个ip过期,即将从IP池中去除该ip')
  54. Ip_Pool.remove(x)
  55. def return_ip_pool(self):
  56. print("ip池线程启动")
  57. for self.ip_pool in self.ip_yield():
  58. pass

5、若需要使用该ip池模块,则需要将文件copy于使用的文件目录下,然后导入文件模块,再创建ip代理类对象,用对象获取ip池(ip_pool)。

6、咱们来回顾下,主程序启动ip代理池后得到ip池,使用ip()方法将ip池处理得到一个随机ip,将ip放入panding方法中请求得到主页源码,再调用is_API_Run.py文件模块下的read_settings_run_func类,继而传入源码创建类对象,在这个文件模块中导入API模块和配置模块,具体功能:根据配置模块创建配置类对象,从而获取到配置信息。然后由API模块创建API类对象,根据配置信息执行相应的方法。以下文件中的打印内容都可以去掉,换成pass占位即可

文件名:is_API_Run.py

  1. '''
  2. 获取配置文件settings的输入给与相应的函数输出
  3. '''
  4. from API_Function import Functions
  5. from settings import configure
  6. class read_settings_run_func():
  7. def __init__(self, page, proxies):
  8. self.proxies = proxies
  9. self.page = page
  10. self.set = configure()
  11. self.func = Functions(self.page, self.proxies)
  12. self.test_settings()
  13. def test_settings(self):
  14. if self.set.Search_hot_words == True:
  15. self.func.Search_hot_words()
  16. else:
  17. print("mei")
  18. if self.set.Editor_s_selection == True:
  19. self.func.Editor_s_selection()
  20. else:
  21. print("mei")
  22. if self.set.Hot_articles == True:
  23. self.func.Hot_articles()
  24. else:
  25. print("mei")
  26. if self.set.Custom_hotspot_source_Text == True:
  27. self.func.Custom_hotspot_source_Text(self.set.text_list)
  28. else:
  29. print("mei")
  30. if self.set.Custom_hotspot_source_Url == True:
  31. self.func.Custom_hotspot_source_Url(self.set.Custom_hotspot_source_Url_List)
  32. else:
  33. print("mei")
  34. if self.set.Hot_event_sources_of_other_websites == True:
  35. self.func.Hot_event_sources_of_other_websites(self.set.Hot_event_sources_of_other_websites_List)
  36. else:
  37. print("mei")
  38. if self.set.input_text == True:
  39. self.func.input_text(self.set.text)
  40. else:
  41. print("mei")
  42. if self.set.Crawling_article == True:
  43. self.func.Crawling_article(self.set.text)
  44. else:
  45. print("mei")
  46. if self.set.Crawling_official_account == True:
  47. self.func.Crawling_official_account()
  48. else:
  49. print("mei")
  50. if self.set.Hot == True:
  51. self.func.Hot()
  52. else:
  53. print("mei")
  54. if self.set.Funny == True:
  55. self.func.Funny()
  56. else:
  57. print("mei")
  58. if self.set.Honyaradoh == True:
  59. self.func.Honyaradoh()
  60. else:
  61. print("mei")
  62. if self.set.Private_talk == True:
  63. self.func.Private_talk()
  64. else:
  65. print("mei")
  66. if self.set.Eight_trigrams == True:
  67. self.func.Eight_trigrams()
  68. else:
  69. print("mei")
  70. if self.set.Technocrats == True:
  71. self.func.Technocrats()
  72. else:
  73. print("mei")
  74. if self.set.Financial_fans == True:
  75. self.func.Financial_fans()
  76. else:
  77. print("mei")
  78. if self.set.Car_control == True:
  79. self.func.Car_control()
  80. else:
  81. print("mei")
  82. if self.set.Life_home == True:
  83. self.func.Life_home()
  84. else:
  85. print("mei")
  86. if self.set.Fashion_circle == True:
  87. self.func.Fashion_circle()
  88. else:
  89. print("mei")
  90. if self.set.Parenting == True:
  91. self.func.Parenting()
  92. else:
  93. print("mei")
  94. if self.set.Travel == True:
  95. self.func.Travel()
  96. else:
  97. print("mei")
  98. if self.set.Workplace == True:
  99. self.func.Workplace()
  100. else:
  101. print("mei")
  102. if self.set.delicious_food == True:
  103. self.func.delicious_food()
  104. else:
  105. print("mei")
  106. if self.set.history == True:
  107. self.func.history()
  108. else:
  109. print("mei")
  110. if self.set.education == True:
  111. self.func.education()
  112. else:
  113. print("mei")
  114. if self.set.constellation == True:
  115. self.func.constellation()
  116. else:
  117. print("mei")
  118. if self.set.Sports == True:
  119. self.func.Sports()
  120. else:
  121. print("mei")
  122. if self.set.military == True:
  123. self.func.military()
  124. else:
  125. print("mei")
  126. if self.set.game == True:
  127. self.func.game()
  128. else:
  129. print("mei")
  130. if self.set.cute_pet == True:
  131. self.func.cute_pet()
  132. else:
  133. print("mei")
  134. if self.set.Home_page_hot == True:
  135. self.func.Home_page_hot()
  136. else:
  137. print("mei")

7、配置文件模块:settings.py,根据用户选择一些爬取方向,设置为True或者False,来判定相应的API函数是否执行,代码如下:

  1. '''
  2. *****配置文件*****
  3. 作用:便于用户设置输入,程序运行时从此文件读取参数属性,以便程序 明确执行 “动作”
  4. '''
  5. set_dir={
  6. # 热点事件爬取(为以下三类)
  7. # 微信公众号热点来源(子集有三类)
  8. # 搜索热词
  9. 'Search_hot_words': True,
  10. # 编辑精选
  11. 'Editor_s_selection': True,
  12. # 热点文章
  13. 'Hot_articles': True,
  14. # 自定义热点来源
  15. # 文本的形式--列表
  16. 'Custom_hotspot_source_Text': True,
  17. # 若 Custom_hotspot_source_List:True 请在此处列表添加热点来源---文本
  18. 'text_list': [],
  19. # 链接的形式--列表
  20. 'Custom_hotspot_source_Url': True,
  21. # 若 Custom_hotspot_source_Url:True 请在此处列表添加热点来源---链接
  22. 'Custom_hotspot_source_Url_List': '[]',
  23. # 其他网站的热点事件来源
  24. # 提取文本--列表
  25. 'Hot_event_sources_of_other_websites': False,
  26. # 若 Hot_event_sources_of_other_websites:True 请在此处列表添加热点事件来源---文本
  27. 'Hot_event_sources_of_other_websites_List': [],
  28. # 输入关键字文本爬取
  29. #在此处输入文本
  30. 'text':[],
  31. 'input_text':False,
  32. # 爬取文章
  33. 'Crawling_article':False,
  34. # 爬取公众号
  35. 'Crawling_official_account':False,
  36. # 微信公众号分类爬取--加载到更多
  37. # 热门
  38. 'Hot':True,
  39. # 搞笑
  40. 'Funny':True,
  41. # 养生堂
  42. 'Honyaradoh':False,
  43. # 私房话
  44. 'Private_talk':False,
  45. # 八卦精
  46. 'Eight_trigrams':False,
  47. # 科技咖
  48. 'Technocrats':False,
  49. # 财经迷
  50. 'Financial_fans':False,
  51. # 汽车控
  52. 'Car_control':False,
  53. # 生活家
  54. 'Life_home':False,
  55. # 时尚圈
  56. 'Fashion_circle':False,
  57. # 育儿
  58. 'Parenting':False,
  59. # 旅游
  60. 'Travel':False,
  61. # 职场
  62. 'Workplace': False,
  63. # 美食
  64. 'delicious_food': False,
  65. # 历史
  66. 'history': False,
  67. # 教育
  68. 'education': False,
  69. # 星座
  70. 'constellation': False,
  71. # 体育
  72. 'Sports': False,
  73. # 军事
  74. 'military': False,
  75. # 游戏
  76. 'game': False,
  77. # 萌宠
  78. 'cute_pet': False,
  79. # 主页热推
  80. 'Home_page_hot': False,
  81. }
  82. class configure():
  83. def __init__(self):
  84. self.Search_hot_words = set_dir.get('Search_hot_words')
  85. self.Editor_s_selection = set_dir.get('Editor_s_selection')
  86. self.Hot_articles = set_dir.get('Hot_articles')
  87. self.Custom_hotspot_source_Text = set_dir.get('Custom_hotspot_source_Text')
  88. self.text_list = set_dir.get('text_list')
  89. self.Custom_hotspot_source_Url = set_dir.get('Custom_hotspot_source_Url')
  90. self.Custom_hotspot_source_Url_List = set_dir.get('Custom_hotspot_source_Url_List')
  91. self.Hot_event_sources_of_other_websites = set_dir.get('Hot_event_sources_of_other_websites')
  92. self.input_text = set_dir.get('input_text')
  93. self.Crawling_article = set_dir.get('Crawling_article')
  94. self.Crawling_official_account = set_dir.get('Crawling_official_account')
  95. self.Hot = set_dir.get('Hot')
  96. self.Funny = set_dir.get('Funny')
  97. self.Honyaradoh = set_dir.get('Honyaradoh')
  98. self.Private_talk = set_dir.get('Private_talk')
  99. self.Eight_trigrams = set_dir.get('Eight_trigrams')
  100. self.Technocrats = set_dir.get('Technocrats')
  101. self.Financial_fans = set_dir.get('Financial_fans')
  102. self.Car_control = set_dir.get('Car_control')
  103. self.Life_home = set_dir.get('Life_home')
  104. self.Fashion_circle = set_dir.get('Fashion_circle')
  105. self.Parenting = set_dir.get('Parenting')
  106. self.Travel = set_dir.get('Travel')
  107. self.Workplace = set_dir.get('Workplace')
  108. self.delicious_food = set_dir.get('delicious_food')
  109. self.history = set_dir.get('history')
  110. self.education = set_dir.get('education')
  111. self.constellation = set_dir.get('constellation')
  112. self.Sports = set_dir.get('Sports')
  113. self.military = set_dir.get('military')
  114. self.game = set_dir.get('game')
  115. self.cute_pet = set_dir.get('cute_pet')
  116. self.Home_page_hot = set_dir.get('Home_page_hot')

8、API文件模块:API_Function.py   定义了一些配置文件中对应的处理函数

API_Function.py:

  1. # 导包
  2. import requests
  3. from bs4 import BeautifulSoup
  4. import pymysql
  5. # 后面发起请求会用到的请求头和请求url
  6. url = 'https://weixin.sogou.com/' # 搜狗微信的入口url链接
  7. headers = {'authority': 'weixin.sogou.com', 'method': 'GET', 'path': '/', 'scheme': 'https',
  8. 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
  9. 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'zh-CN,zh;q=0.9', 'cache-control': 'max-age=0',
  10. 'cookie': 'ABTEST=7|1619743404|v1; IPLOC=CN3205; SUID=5E9A50754018960A00000000608B52AC; SUID=5E9A5075AF21B00A00000000608B52AC; weixinIndexVisited=1; SUV=0087AD4475509A5E608B52ADF7A81201; SNUID=CD8A73542124E19CE9C1C01321869CD8; JSESSIONID=aaaUz7AAKRNv6gHXIfJGx',
  11. 'sec-fetch-dest': 'document', 'sec-fetch-mode': 'navigate', 'sec-fetch-site': 'none', 'sec-fetch-user': '?1',
  12. 'upgrade-insecure-requests': '1',
  13. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36 SLBrowser/7.0.0.4071 SLBChan/15'}
  14. class Functions():
  15. def __init__(self, page, proxies):
  16. # 代理
  17. self.proxies = proxies
  18. # 搜狗微信主页的网页源码
  19. self.page = page
  20. # bs4初始化网页源码
  21. self.soup = BeautifulSoup(self.page, 'lxml')
  22. # 连接mysql数据库,返回一个数据库对象
  23. self.coon = pymysql.connect(user='root', password='clly0528', db='gc')
  24. # 创建游标对象,方便后续执行sql语句操作
  25. self.cur = self.coon.cursor()
  26. # 删除已存在的同名的数据表
  27. self.clear_database()
  28. def clear_database(self):
  29. self.cur.execute("show tables like 'urls'")
  30. if len(self.cur.fetchall()) == 0:
  31. print("创建表")
  32. # 创建表
  33. self.cur.execute('''create table urls(id int not NULL auto_increment,
  34. href varchar(500) not NULL,
  35. title varchar(500) not NULL,
  36. primary key (id)
  37. );''')
  38. else:
  39. # 删除表
  40. self.cur.execute("drop table urls")
  41. self.coon.commit()
  42. # 创建表
  43. print(30 * '-' + "删除原表,创建新表!" + 30 * '-')
  44. self.cur.execute('''create table urls(id int auto_increment primary key,
  45. href varchar(500) not NULL,
  46. title varchar(500) not NULL
  47. );''')
  48. #提交保存
  49. self.coon.commit()
  50. # ***********************************************************************************************************************
  51. def Search_hot_words(self): # 搜索热词
  52. for tag in self.soup.select('#topwords > li > a'): # 罗列出每个tga标签对象的href属性与title属性
  53. sql = r"insert into urls(href,title) value(" + "'" + tag.attrs['href'] + "'" + ',' + "'" + tag.attrs[
  54. 'title'] + "'" + ")"
  55. print("搜索热词sql: ", sql)
  56. self.cur.execute(sql)
  57. self.coon.commit()
  58. def Editor_s_selection(self): # 编辑精选
  59. p_soup_list = self.soup.select(".aside >p")
  60. for p_soup in p_soup_list:
  61. if p_soup.get_text() == "编辑精选":
  62. a_soup = p_soup.find_next("ul").select('li >.txt-box > .p1 >a')
  63. for tag in a_soup:
  64. sql = r"insert into urls(href,title) value(" + "'" + tag.attrs['href'] + "'" + ',' + "'" + \
  65. tag.attrs[
  66. 'title'] + "'" + ")"
  67. print("编辑精选sql: ", sql)
  68. self.cur.execute(sql)
  69. self.coon.commit()
  70. def Hot_articles(self): # 热点文章
  71. p_soup_list = self.soup.select(".aside >p")
  72. for p_soup in p_soup_list:
  73. if p_soup.get_text() == "热点文章":
  74. a_soup = p_soup.find_next("ul").select('li >.txt-box > .p1 >a')
  75. for tag in a_soup:
  76. sql = r"insert into urls(href,title) value(" + "'" + tag.attrs['href'] + "'" + ',' + "'" + \
  77. tag.attrs[
  78. 'title'] + "'" + ")"
  79. print("热点文章sql: ", sql)
  80. self.cur.execute(sql)
  81. self.coon.commit()
  82. def Custom_hotspot_source_Text(self, text_list): # 自定义热点文本
  83. a = "https://weixin.sogou.com/weixin?type=2&s_from=input&query="
  84. for text in text_list:
  85. response = requests.get(a + text, headers=headers, proxies=self.proxies)
  86. print(response.text)
  87. def Custom_hotspot_source_Url(self, url_list): # 热点来源---链接
  88. pass
  89. def Hot_event_sources_of_other_websites(self, list): # 选定某个网站作为外来热点来源-----写个爬虫去定向的爬取该网站的热点作为文本输入
  90. pass
  91. def input_text(self, text_list): # 搜文章
  92. a = "https://weixin.sogou.com/weixin?type=2&s_from=input&query="
  93. for text in text_list:
  94. response = requests.get(a + text, headers=headers, proxies=self.proxies)
  95. print(response.text)
  96. def Crawling_article(self, text_list): # 搜公众号
  97. a = "https://weixin.sogou.com/weixin?type=1&s_from=input&query="
  98. for text in text_list:
  99. response = requests.get(a + text, headers=headers, proxies=self.proxies)
  100. print(response.text)
  101. def Hot(self, num=20, pd=0): # 分类--热门--提取相关文章链接 flag=False, 是否加载更多,默认加载20条,num=20,自定义加载多少条
  102. pn = 0
  103. if num > 20:
  104. pn = num / 20
  105. for n in range(pn):
  106. self.pc(n)
  107. print("再一次执行这个函数")
  108. return "函数已执行完!"
  109. else:
  110. self.pc(pn, pd)
  111. # ----------------------------- 开始 pc()函数为分类爬取中所需的常用函数,所以单独提出来。--------------------------------------
  112. def pc(self, pn, pd):
  113. if pn >= 1:
  114. url = "https://weixin.sogou.com/pcindex/pc/pc_" + str(pd) + "/" + str(pn) + ".html"
  115. else:
  116. url = "https://weixin.sogou.com/pcindex/pc/pc_" + str(pd) + "/pc_" + str(pd) + ".html"
  117. print("url:", url)
  118. a = "li > .txt-box > h3 > a "
  119. res = requests.get(url, headers=headers, proxies=self.proxies).content.decode("utf8")
  120. self.soup = BeautifulSoup(res, 'lxml')
  121. a_soup = self.soup.select(a)
  122. print(a_soup)
  123. for tag in a_soup:
  124. sql = r"insert into urls(href,title) value(" + "'" + tag.attrs['href'] + "'" + ',' + "'" + \
  125. tag.text + "'" + ")"
  126. print("分类--热门sql: ", sql)
  127. self.cur.execute(sql)
  128. self.coon.commit()
  129. # ---------------------------- 结束 pc() ----------------------------------------------------------------------------
  130. def Funny(self, num=20, pd=1):
  131. print("Funny")
  132. pn = 0
  133. if num > 20:
  134. pn = num / 20
  135. for n in range(pn):
  136. self.pc(n, pd)
  137. print("再一次执行这个函数")
  138. return "函数已执行完!"
  139. else:
  140. self.pc(pn, pd)
  141. print("可以")
  142. def Honyaradoh(self, num=20, pd=2):
  143. pn = 0
  144. if num > 20:
  145. pn = num / 20
  146. for n in range(pn, pd):
  147. self.pc(n, pd)
  148. print("再一次执行这个函数")
  149. return "函数已执行完!"
  150. else:
  151. self.pc(pn, pd)
  152. def Private_talk(self, num=20, pd=3):
  153. pn = 0
  154. if num > 20:
  155. pn = num / 20
  156. for n in range(pn):
  157. self.pc(n, pd)
  158. print("再一次执行这个函数")
  159. return "函数已执行完!"
  160. else:
  161. self.pc(pn, pd)
  162. def Eight_trigrams(self, num=20, pd=4):
  163. pn = 0
  164. if num > 20:
  165. pn = num / 20
  166. for n in range(pn):
  167. self.pc(n, pd)
  168. print("再一次执行这个函数")
  169. return "函数已执行完!"
  170. else:
  171. self.pc(pn, pd)
  172. def Technocrats(self, num=20, pd=5):
  173. pn = 0
  174. if num > 20:
  175. pn = num / 20
  176. for n in range(pn):
  177. self.pc(n, pd)
  178. print("再一次执行这个函数")
  179. return "函数已执行完!"
  180. else:
  181. self.pc(pn, pd)
  182. def Financial_fans(self, num=20, pd=6):
  183. pn = 0
  184. if num > 20:
  185. pn = num / 20
  186. for n in range(pn):
  187. self.pc(n, pd)
  188. print("再一次执行这个函数")
  189. return "函数已执行完!"
  190. else:
  191. self.pc(pn, pd)
  192. def Car_control(self, num=20, pd=7):
  193. pn = 0
  194. if num > 20:
  195. pn = num / 20
  196. for n in range(pn):
  197. self.pc(n, pd)
  198. print("再一次执行这个函数")
  199. return "函数已执行完!"
  200. else:
  201. self.pc(pn, pd)
  202. def Life_home(self, num=20, pd=8):
  203. pn = 0
  204. if num > 20:
  205. pn = num / 20
  206. for n in range(pn):
  207. self.pc(n, pd)
  208. print("再一次执行这个函数")
  209. return "函数已执行完!"
  210. else:
  211. self.pc(pn, pd)
  212. def Fashion_circle(self, num=20, pd=9):
  213. pn = 0
  214. if num > 20:
  215. pn = num / 20
  216. for n in range(pn):
  217. self.pc(n, pd)
  218. print("再一次执行这个函数")
  219. return "函数已执行完!"
  220. else:
  221. self.pc(pn, pd)
  222. def Parenting(self, num=20, pd=10):
  223. pn = 0
  224. if num > 20:
  225. pn = num / 20
  226. for n in range(pn):
  227. self.pc(n, pd)
  228. print("再一次执行这个函数")
  229. return "函数已执行完!"
  230. else:
  231. self.pc(pn, pd)
  232. def Travel(self, num=20, pd=11):
  233. pn = 0
  234. if num > 20:
  235. pn = num / 20
  236. for n in range(pn):
  237. self.pc(n, pd)
  238. print("再一次执行这个函数")
  239. return "函数已执行完!"
  240. else:
  241. self.pc(pn, pd)
  242. def Workplace(self, num=20, pd=12):
  243. pn = 0
  244. if num > 20:
  245. pn = num / 20
  246. for n in range(pn):
  247. self.pc(n, pd)
  248. print("再一次执行这个函数")
  249. return "函数已执行完!"
  250. else:
  251. self.pc(pn, pd)
  252. def delicious_food(self, num=20, pd=13):
  253. pn = 0
  254. if num > 20:
  255. pn = num / 20
  256. for n in range(pn):
  257. self.pc(n, pd)
  258. print("再一次执行这个函数")
  259. return "函数已执行完!"
  260. else:
  261. self.pc(pn, pd)
  262. def history(self, num=20, pd=14):
  263. pn = 0
  264. if num > 20:
  265. pn = num / 20
  266. for n in range(pn):
  267. self.pc(n, pd)
  268. print("再一次执行这个函数")
  269. return "函数已执行完!"
  270. else:
  271. self.pc(pn, pd)
  272. def education(self, num=20, pd=15):
  273. pn = 0
  274. if num > 20:
  275. pn = num / 20
  276. for n in range(pn):
  277. self.pc(n, pd)
  278. print("再一次执行这个函数")
  279. return "函数已执行完!"
  280. else:
  281. self.pc(pn, pd)
  282. def constellation(self, num=20, pd=16):
  283. pn = 0
  284. if num > 20:
  285. pn = num / 20
  286. for n in range(pn):
  287. self.pc(n, pd)
  288. print("再一次执行这个函数")
  289. return "函数已执行完!"
  290. else:
  291. self.pc(pn, pd)
  292. def Sports(self, num=20, pd=17):
  293. pn = 0
  294. if num > 20:
  295. pn = num / 20
  296. for n in range(pn):
  297. self.pc(n, pd)
  298. print("再一次执行这个函数")
  299. return "函数已执行完!"
  300. else:
  301. self.pc(pn, pd)
  302. def military(self, num=20, pd=18):
  303. pn = 0
  304. if num > 20:
  305. pn = num / 20
  306. for n in range(pn):
  307. self.pc(n, pd)
  308. print("再一次执行这个函数")
  309. return "函数已执行完!"
  310. else:
  311. self.pc(pn, pd)
  312. def game(self, num=20, pd=19):
  313. pn = 0
  314. if num > 20:
  315. pn = num / 20
  316. for n in range(pn):
  317. self.pc(n, pd)
  318. print("再一次执行这个函数")
  319. return "函数已执行完!"
  320. else:
  321. self.pc(pn, pd)
  322. def cute_pet(self, num=20, pd=20):
  323. pn = 0
  324. if num > 20:
  325. pn = num / 20
  326. for n in range(pn):
  327. self.pc(n, pd)
  328. print("再一次执行这个函数")
  329. return "函数已执行完!"
  330. else:
  331. self.pc(pn, pd)
  332. def Home_page_hot(self, num=20, pd=21):
  333. pn = 0
  334. if num > 20:
  335. pn = num / 20
  336. for n in range(pn):
  337. self.pc(n, pd)
  338. print("再一次执行这个函数")
  339. return "函数已执行完!"
  340. else:
  341. self.pc(pd)

线程池文件:thread_pool.py

  1. #导包
  2. from multiprocessing import cpu_count
  3. import threading
  4. import requests
  5. import queue
  6. import pymysql
  7. import time
  8. '''
  9. pymysql创建一个coon数据库对象,将数据库中的重复链接去重(变唯一),把所有的链接拿出来放到队列中去(需要定义队列对象--初始化队列对象)
  10. 从队列中拿出数据分给线程去处理,注意:拿出数据的这个动作它是唯一的(就是只能每次一个线程去拿----加锁--锁定只能一个线程拿---线程锁)
  11. 编写线程函数--每个线程函数内容皆一样(都是去下载html页面,用到的是requests库),将数据放到数据库中-建表--方便后面数据清洗
  12. '''
  13. class Open_Thread_Assign_Links(): # 开启线程,分配链接
  14. def __init__(self,proxies):
  15. # 请求头
  16. self.headers = {'authority': 'weixin.sogou.com', 'method': 'GET', 'path': '/', 'scheme': 'https',
  17. 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
  18. 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'zh-CN,zh;q=0.9',
  19. 'cache-control': 'max-age=0',
  20. 'cookie': 'ABTEST=7|1619743404|v1; IPLOC=CN3205; SUID=5E9A50754018960A00000000608B52AC; SUID=5E9A5075AF21B00A00000000608B52AC; weixinIndexVisited=1; SUV=0087AD4475509A5E608B52ADF7A81201; SNUID=CD8A73542124E19CE9C1C01321869CD8; JSESSIONID=aaaUz7AAKRNv6gHXIfJGx',
  21. 'sec-fetch-dest': 'document', 'sec-fetch-mode': 'navigate', 'sec-fetch-site': 'none',
  22. 'sec-fetch-user': '?1', 'upgrade-insecure-requests': '1',
  23. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36 SLBrowser/7.0.0.4071 SLBChan/15'}
  24. #创建锁对象
  25. self.lock = threading.Lock()
  26. #确定线程数
  27. self.Mul_Num()
  28. # 代理
  29. self.proxies=proxies
  30. #创建队列
  31. self.q = queue.Queue(500)
  32. # 从数据库中取出url数据
  33. self.url_tuple = self.get()
  34. # 将链接压进队列
  35. self.Push_Element_Queue(self.url_tuple)
  36. # 启动线程处理队列
  37. self.Run_thread()
  38. def get(self): # 从数据库中取出url数据 #便于初始化类时从数据库中拿出数据,也方便后续界面用户发起的请求
  39. coon = pymysql.connect(user='root', password='clly0528', db='gc')
  40. cur = coon.cursor()
  41. cur.execute('select * from urls')
  42. urls_list = cur.fetchall()
  43. # print("*:",urls_list)
  44. return urls_list
  45. def Push_Element_Queue(self, urls_list):
  46. for tuple_x in urls_list:
  47. self.q.put(tuple_x[1]) #将链接压进队列
  48. # print("q:",self.q)
  49. def Run_thread(self):
  50. cut=0
  51. for thread_id in range(self.mul_num):
  52. cut+=1
  53. threading.Thread(target=self.spider,args=(self.q,cut)).start()
  54. print("已成功开启%d个线程" % self.mul_num)
  55. # 线程函数
  56. def spider(self,lq,cut):
  57. print("开启线程 %d ...." % cut)
  58. while True:
  59. while lq.empty:
  60. # 加锁
  61. self.lock.acquire()
  62. # 保证这个动作单一,同一时间只能由一个线程主管
  63. url = lq.get(block=True, timeout=None)
  64. # 解锁
  65. self.lock.release()
  66. # 这里获取到返回体,将返回体通过yield关键字传递给数据处理类。。
  67. print("下载文章...")
  68. responese=requests.get(url=url,headers=self.headers,proxies=self.proxies)
  69. # 文章内容写入磁盘
  70. Generate_file(responese)
  71. # 确定开启几个线程
  72. def Mul_Num(self):
  73. # x: cpu实际运行时间 y: 线程等待时间
  74. N = cpu_count()
  75. x = 1
  76. y = 5
  77. self.mul_num = int(N * (x + y) / x)
  78. # 将下载后的文章写入磁盘html_page中
  79. def Generate_file(responese):
  80. print("文章写入文件夹")
  81. with open(r'C:\Users\Windows_pycharm\Desktop\G\图书管理系统\微信公众号爬取\html_page'+'\\'+time.strftime('%Y%m%d%H%M%S') + '.txt','w',encoding='utf-8') as f:
  82. f.write(responese.text)

 

 

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/786115
推荐阅读
相关标签
  

闽ICP备14008679号