python 微信爬虫实例

时间:2022-12-12 13:39:58

单线程版:

 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. JAZZ

    今天知道公司中的JAZZ是变形金刚中的“爵士”,如果写内部代码,就好像在操作“爵士”,还是蛮有意思的.先是接触了jQuery,然后是jQuery-ui,然后jazz,继续中...... JAZZ: 爵 ...

  2. 【hibernate】之标注枚举类型&commat;Enumerated&lpar;转载&rpar;

    实体Entity中通过@Enumerated标注枚举类型,例如将CustomerEO实体中增加一个CustomerType类型的枚举型属性,标注实体后的代码如下所示. @Entity @Table(n ...

  3. Codeforces Round &num;306 &lpar;Div&period; 2&rpar; C&period; Divisibility by Eight 暴力

    C. Divisibility by Eight Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/ ...

  4. 二、Mysql(二)

    原文参考:http://www.cnblogs.com/wupeiqi/articles/5713323.html 还有一个是课件,看着也像博客,但不知道是谁的 内置函数 触发器 存储过程 索引 与p ...

  5. 【由浅入深理解java集合】&lpar;二&rpar;——集合 Set

    上一篇文章介绍了Set集合的通用知识.Set集合中包含了三个比较重要的实现类:HashSet.TreeSet和EnumSet.本篇文章将重点介绍这三个类. 一.HashSet类 HashSet简介 H ...

  6. fidder显示 请求响应时间

    在顶部的工具栏找到 Rules->CustomRules,第一次打开会弹出提示要安装Fiddler Script 工具,选择 [否], 就会打开 CustomRules.js 文件. 在 cla ...

  7. STL 的 vector 根据元素的值来删除元素的方法

    vector 的 erase( ) 只能删除迭代器,所以要想删某种值的元素,需要这样: 假设有一个 vector 叫 vt ,则 vt.erase( remove( vt.begin() , vt.e ...

  8. 深入理解Aspnet Core之Identity&lpar;5&rpar;

    主题 本篇我将会介绍验证用户的机制当账户被创建的时候,同样 这个过程主要有IUserValidator这个接口来实现的,和密码验证一样Identity同样也内置已经实现好的账户验证.账户验证的比较简单 ...

  9. SQL中常见语句

    SQL中常见语句笔记: --替换字段中的回车符和换行符 ) ), '') --删除表命令 DROP TABLE [dbo].[MGoods_Test] --删除表中数据命令 DELETE FROM [ ...

  10. MessagingTimeout&colon; Timed out waiting for a reply to message ID

    l3中出现大量消息超时错误,对网络的操作各种异常. 报错如下: 2016-02-25 05:54:59.886 15110 ERROR neutron.agent.l3.agent [req-db92 ...