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) + '篇文章失败')

猜你喜欢

转载自blog.csdn.net/xx20cw/article/details/84306647
今日推荐