单线程版:

 import  urllib.request
import urllib.parse
import urllib.error
import re,time
headers = ("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3107.4 Safari/537.36")
operner = urllib.request.build_opener()
operner.addheaders = [headers]
urllib.request.install_opener(operner) list_url = [] ###使用代理获取网页url内容
def use_proxy(url):
try:
# proxy = urllib.request.ProxyHandler({'http':proxy_addr})    ##使用代理版
# operner = urllib.request.build_opener()
# urllib.request.install_opener(operner)
headers = ("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3107.4 Safari/537.36")
operner = urllib.request.build_opener()
operner.addheaders = [headers]
urllib.request.install_opener(operner)
data = urllib.request.urlopen(url).read().decode('utf-8')
# print (data)
return data
except urllib.error.URLError as e:
if hasattr(e, "code"):
print(e.code)
elif hasattr(e, "reason"):
print(e.reason) except Exception as e:
print("exception" + str(e))
time.sleep(1) ##获取要爬取的url
def get_url(key, pagestart, pageend):
try: keycode = urllib.parse.quote(key) for page in range(pagestart, pageend + 1):
url = "http://weixin.sogou.com/weixin?query=%s&_sug_type_=&s_from=input&_sug_=n&type=%d&page=1&ie=utf8" % (
keycode, page)
data1 = use_proxy(url)
#print("data1的内容是", data1)
listurl_pattern = '<h3>.*?("http://.*?)</h3>'
result = re.compile(listurl_pattern, re.S).findall(data1)
for i in range(len(result)):
res = result[i].replace("amp;", "").split(" ")[0].replace("\"", "")
list_url.append(res)
#print(list_url)
return list_url
except urllib.error.URLError as e:
if hasattr(e, "code"):
print(e.code)
elif hasattr(e, "reason"):
print(e.reason)
except Exception as e:
print("exception:", e) ##通过获取的url爬行内容数据并处理
def get_url_content(list_url):
fh1=open("D:\\python-script\\1.html", 'wb')
html1 = '''<!DOCTYPE html>\n<html xmlns="http://www.w3.org/1999/xhmtl">\n<head>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n<title>微信文章</title></head>\n<body>'''
fh1.write(html1.encode("utf-8"))
fh1.close()
fh = open("D:\\python-script\\1.html", 'ab')
for url in list_url:
data_content = use_proxy(url)
#print (data_content)
#sys.exit()
title_pattern = '<h2.*>.*?</h2>'
result_title = re.compile(title_pattern, re.S).findall(data_content)
##标题(str)
res_title = result_title[0].replace("<h2 class=\"rich_media_title\" id=\"activity-name\">", "").replace("</h2>",
"").strip() content_pattern = 'id="js_content">(.*?)<div class="rich_media_tool" id="js_sg_bar">'
content = re.compile(content_pattern, re.S).findall(data_content) try:
fh.write(res_title.encode("utf-8"))
for i in content:
fh.write(i.strip().encode("utf-8"))
except UnicodeEncodeError as e:
continue fh.write("</body></html>".encode("utf-8")) if __name__ == '__main__':
pagestart = 1
pageend = 2
key = "人工智能"
get_url(key, pagestart, pageend)
get_url_content(list_url)

多线程版:

import  urllib.request
import urllib.parse
import urllib.error
import re,time
import queue
import threading headers = ("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3107.4 Safari/537.36")
operner = urllib.request.build_opener()
operner.addheaders = [headers]
urllib.request.install_opener(operner) urlque = queue.Queue()
list_url = [] ###使用代理获取网页url内容
def use_proxy(url):
try:
# proxy = urllib.request.ProxyHandler({'http':proxy_addr})
# operner = urllib.request.build_opener()
# urllib.request.install_opener(operner)
headers = ("User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3107.4 Safari/537.36")
operner = urllib.request.build_opener()
operner.addheaders = [headers]
urllib.request.install_opener(operner)
data = urllib.request.urlopen(url).read().decode('utf-8')
#print (data)
return data
except urllib.error.URLError as e:
if hasattr(e,"code"):
print (e.code)
elif hasattr(e,"reason"):
print (e.reason) except Exception as e:
print ("exception"+str(e))
time.sleep(1) ###获取文章的url连接,并将连接加入到队列
class get_url(threading.Thread):
def __init__(self,key,pagestart,pageend,urlque):
threading.Thread.__init__(self)
self.pagestart = pagestart
self.pageend = pageend
self.key = key
self.urlque = urlque def run(self):
try:
keycode = urllib.parse.quote(self.key) for page in range(self.pagestart,self.pageend+1):
url = "http://weixin.sogou.com/weixin?query=%s&_sug_type_=&s_from=input&_sug_=n&type=%d&page=1&ie=utf8" % (keycode,page)
data = use_proxy(url)
print ("data1的内容是",data)
listurl_pattern = '<h3>.*?("http://.*?)</h3>'
result = re.compile(listurl_pattern,re.S).findall(data)
print (result)
if len(result) == 0:
print ("没有可用的url")
sys.exit()
for i in range(len(result)):
res = result[i].replace("amp;","").split(" ")[0].replace("\"" ,"")
#list_url.append(res) #加入列表
self.urlque.put(res) ##加入队列
self.urlque.task_done() #return list_url
except urllib.error.URLError as e:
if hasattr(e, "code"):
print(e.code)
elif hasattr(e, "reason"):
print(e.reason)
except Exception as e:
print ("exception:",e) ##根据url获取文章内容
class get_url_content(threading.Thread):
def __init__(self,urlque):
threading.Thread.__init__(self)
self.urlque = urlque def run(self):
fh1 = open("D:\\python-script\\1.html", 'wb')
html1 = '''<!DOCTYPE html>\n<html xmlns="http://www.w3.org/1999/xhmtl">\n<head>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n<title>微信文章</title></head>\n<body>'''
fh1.write(html1.encode("utf-8"))
fh1.close()
fh = open("D:\\python-script\\1.html", 'ab')
while True:
try:
url = self.urlque.get()
data_content = use_proxy(url) title_pattern = '<h2.*>.*?</h2>'
result_title = re.compile(title_pattern, re.S).findall(data_content)
##标题
res_title = result_title[0].replace("<h2 class=\"rich_media_title\" id=\"activity-name\">", "").replace("</h2>","").strip() content_pattern = 'id="js_content">(.*?)<div class="rich_media_tool" id="js_sg_bar">'
content = re.compile(content_pattern, re.S).findall(data_content)
#c = '<p style="max-width: 100%;box-sizing: border-box;min-height: 1em;text-indent: 2em;word-wrap: break-word !important;">'
# for i in content:
# ##内容
# c_content=i.replace(c, "").replace("<br /></p>", "").replace("</p>", "") fh.write(res_title.encode("utf-8"))
for i in content:
fh.write(i.strip().encode("utf-8"))
except UnicodeEncodeError as e:
continue fh.close()
class contrl(threading.Thread):
def __init__(self,urlqueue):
threading.Thread.__init__(self) self.urlqueue = urlqueue
while True:
print ("程序正在执行")
if self.urlqueue.empty():
time.sleep(3)
print ("程序执行完毕")
exit() if __name__ == '__main__':
pagestart = 1
pageend = 2
key = "人工智能"
get_url = get_url(key,pagestart,pageend,urlque) get_url.start() get_content = get_url_content(urlque)
get_content.start() cntrol = contrl(urlque)
cntrol.start()

  

python 微信爬虫实例的更多相关文章

  1. Python 多进程爬虫实例

    Python  多进程爬虫实例 import json import re import time from multiprocessing import Pool import requests f ...

  2. python scrapy 爬虫实例

    1 创建一个项目 scrapy startproject basicbudejie 2 编写爬虫 import scrapy class Basicbudejie(scrapy.Spider): na ...

  3. python 多线程爬虫 实例

    多进程 Multiprocessing 模块 Process 类用来描述一个进程对象.创建子进程的时候,只需要传入一个执行函数和函数的参数即可完成 Process 示例的创建. star() 方法启动 ...

  4. Python小爬虫实例

    有几个注意点: # -*- coding: utf-8 -*- # func passport jw.qdu.edu.cn import re import urllib# python3后urlli ...

  5. Python 爬虫实例

    下面是我写的一个简单爬虫实例 1.定义函数读取html网页的源代码 2.从源代码通过正则表达式挑选出自己需要获取的内容 3.序列中的htm依次写到d盘 #!/usr/bin/python import ...

  6. 如何利用Python网络爬虫抓取微信朋友圈的动态(上)

    今天小编给大家分享一下如何利用Python网络爬虫抓取微信朋友圈的动态信息,实际上如果单独的去爬取朋友圈的话,难度会非常大,因为微信没有提供向网易云音乐这样的API接口,所以很容易找不到门.不过不要慌 ...

  7. 如何利用Python网络爬虫爬取微信朋友圈动态--附代码(下)

    前天给大家分享了如何利用Python网络爬虫爬取微信朋友圈数据的上篇(理论篇),今天给大家分享一下代码实现(实战篇),接着上篇往下继续深入. 一.代码实现 1.修改Scrapy项目中的items.py ...

  8. Python爬虫实例:爬取B站《工作细胞》短评——异步加载信息的爬取

    很多网页的信息都是通过异步加载的,本文就举例讨论下此类网页的抓取. <工作细胞>最近比较火,bilibili 上目前的短评已经有17000多条. 先看分析下页面 右边 li 标签中的就是短 ...

  9. Python爬虫实例:爬取猫眼电影——破解字体反爬

    字体反爬 字体反爬也就是自定义字体反爬,通过调用自定义的字体文件来渲染网页中的文字,而网页中的文字不再是文字,而是相应的字体编码,通过复制或者简单的采集是无法采集到编码后的文字内容的. 现在貌似不少网 ...

随机推荐

  1. Nginx 优先选择连接最少的上游服务器

    详见陶辉87课 upstream test { server ; server ; least_conn ; zone backends 64k; }

  2. 实验吧 WEB 貌似有点难

    错误!你的IP不在允许列表之内! 提示:代码审计 这个提示可谓是非常良心了,一看源代码是一个识别ip地址的东西,如果IP为1.1.1.1那么就会得到KEY. 第一个if是判断是否有client-ip ...

  3. python第三方库的四种安装方法

    1,直接pip install安装 2,在python-->default setting-->project interprer-->add 3,在这个链接里找到需要的包,下载 h ...

  4. python中的split()方法的使用

    Python split()方法:通过指定分隔符对字符串进行分割并返回一个列表,默认分隔符为所有空字符,包括空格.换行(\n).制表符(\t)等. l  Str.split()默认以空格,换行\n,制 ...

  5. 志愿者招募 HYSBZ - 1061(公式建图费用流)

    转自神犇:https://www.cnblogs.com/jianglangcaijin/p/3799759.html 题意:申奥成功后,布布经过不懈努力,终于 成为奥组委下属公司人力资源部门的主管. ...

  6. 阿里云上,Ubuntu下配置Nginx,在tomcat中加了https协议就不可以了

    问题 阿里云上,Ubuntu服务器,本来部署的是tomcat,并且使用了https 协议.后来为了静态资源分离集成了 nginx,nginx代理跳转到 tomcat.刚开始直接访问http 网址发现, ...

  7. ZOJ 3846 GCD Reduce//水啊水啊水啊水

    GCD Reduce Time Limit: 2 Seconds      Memory Limit: 65536 KB      Special Judge You are given a sequ ...

  8. 反射中Class.forName()和classLoader的区别

    搞清楚两者之间区别前,我们来了解下类加载过程. 一.类加载过程 1.加载 通过一个类的全限定名来获取定义此类的二进制字节流. 将这个字节流所代表的静态存储结构转化为方法区的运行时数据结构. 在内存中生 ...

  9. 06 Zabbix4.0系统CISCO交换机告警模板规划信息(基础)

    点击返回:自学Zabbix之路 点击返回:自学Zabbix4.0之路 点击返回:自学zabbix集锦 06 Zabbix4.0系统CISCO交换机告警模板规划信息(基础) 1. Host groups ...

  10. BZOJ5262(容斥)

    题目描述 听着自己美妙的曲子,小Z进入了梦乡.在梦中,小Z仿佛又回到了自己纵横考场的年代.在梦中,小Z参加了一场 考试,这场考试一共有n道题,每道题的最终得分都是一个大于等于0的整数.然而醒来后,小Z ...