python微信爬虫

微信网站为http://weixin.sogou.com/

微信爬虫,使用代理服务器爬一个网址。注意设置代理服务器时,该代理服务器有可能失效,需要换成新的有效代理服务器。代理服务器可以百度到。

import urllib.request
import re
import time
import urllib.error


# 自定义函数,功能为使用代理服务器爬一个网址
def use_proxy(proxy_addr, url):
    # 异常处理机制
    try:
        req = urllib.request.Request(url)  # Request模拟浏览器
        req.add_header = ('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/63.0')
        proxy = urllib.request.ProxyHandler({'http': proxy_addr})  # 代理服务器
        opener = urllib.request.build_opener(proxy, urllib.request.HTTPHandler)
        urllib.request.install_opener(opener)
        data = urllib.request.urlopen(req).read()
        return data
    except urllib.error.URLError as e:
        if hasattr(e, 'code'):  # 判断是否有状态码
            print(e.code)
        if hasattr(e, 'reason'):  # 判断是否有原因这个属性
            print(e.reason)
        # 若为URLError异常,延时10秒执行
        time.sleep(10)
    except Exception as e:
        print('exception:' + str(e))
        # 若为Exception异常,延时1秒执行
        time.sleep(1)


# 设置关键词
key = 'Python'
# 设置代理服务器,该代理服务器有可能失效,读者需要换成新的有效代理服务器
proxy = '127.0.0.1:8888'
# 爬多少页
for i in range(0, 10):
    key = urllib.request.quote(key)
    thispageurl = 'https://weixin.sogou.com/weixin?query=' + key + '&type=2&page=' + str(i)

    thispagedata = use_proxy(proxy, thispageurl)

    pat1 = '<a target="_blank" href="(.*?)"'
    rs1 = re.compile(pat1, re.S).findall(str(thispagedata))
    if (len(rs1) == 0):
        print('此次(' + str(i) + '页)没成功')
        continue
    for j in range(0, len(rs1)):
        thisurl = rs1[j]
        thisurl = thisurl.replace('amp;', '')
        file = 'e:/image/第' + str(i) + '页第' + str(j) + '篇文章.html'
        thisdata = use_proxy(proxy, thisurl)
        print(len(thisdata))
        try:
            fh = open(file, 'wb')
            fh.write(thisdata)
            fh.close()
            print('第' + str(i) + '页第' + str(j) + '篇文章成功')
        except Exception as e:
            print(e)
            print('第' + str(i) + '页第' + str(j) + '篇文章失败')

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值