单线程版:

 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. 百年老图难倒谷歌AI,兔还是鸭?这是个问题

    上面这张图,画的是鸭子还是兔子? 自从1892年首次出现在一本德国杂志上之后,这张图就一直持续引发争议.有些人只能看到一只兔子,有些人只能看到一只鸭子,有些人两个都能看出来. 心理学家用这张图证明了一 ...

  2. zabbix在执行docker命令是报错

    系统环境 ubuntu 14.04  x64 安装了zabbix,去监控docker的状态,安装zabbix见我的另外一篇文章 错误如下 WARNING: Error loading config f ...

  3. Typora——安装Pandoc

    安装 打开typora,帮助-> Install and Use Pandoc  |  访问在线地址 https://support.typora.io/Install-and-Use-Pand ...

  4. CDQ题目套路总结 [未完成]

    CDQ学习资料 day1cdq分治相关 CDQ的IOI论文 1.优化斜率dp 左边对右边影响维护一个凸包解决 需要知识:①凸包②斜率dp 题目:√ HDU3842 Machine Works   HY ...

  5. 使用Putty执行Rsync命令

    背景介绍:公司的文件服务器有多个,一个Master服务器,10个左右的Slave服务器. 当Master服务器中的文件更新之后,Slave服务器中的文件也必须做相对应的同步操作. 公司目前使用的Rsy ...

  6. HNOI2019 退役记

    窗外风雨大作. 凌晨两点又被噩梦惊醒,朦胧中看见书桌的灯还亮着. 走近书桌,有一个人正在敲打着键盘,屏幕上是一些似曾相识的东西. 被水浸湿的头发随意地搭在额头上,鼻梁上架着一副眼镜,镜片上全是小水珠, ...

  7. 自学Python之路-Python并发编程+数据库+前端

    自学Python之路-Python并发编程+数据库+前端 自学Python之路[第一回]:1.11.2 1.3

  8. 【BZOJ3925】[ZJOI2015]地震后的幻想乡(动态规划)

    [BZOJ3925][ZJOI2015]地震后的幻想乡(动态规划) 题面 BZOJ 洛谷 题解 题目里面有一句提示:对于\(n\)个\([0,1]\)之间的随机变量\(x1,x2,...,xn\),第 ...

  9. python服务器文件上传下载+GUI【tkinter】

    大概就是一个通过应用程序来和服务器打交道的这么一个,小东西 1.GUI 用的是tkinter # -*- coding: UTF-8 -*- from tkinter import * import ...

  10. Codeforces 1051E. Vasya and Big Integers

    题意:给你N个点M条边,M-N<=20,有1e5个询问,询问两点的最短距离.保证没有自环和重边. 题解:连题目都在提示你这个20很有用,所以如果是颗树的话那任意两点的最短距离就是求一下lca搞一 ...