python爬取指定微信公众号文章
本文实例为大家分享了python爬取微信公众号文章的具体代码,供大家参考,具体内容如下
该方法是依赖于urllib2库来完成的,首先你需要安装好你的python环境,然后安装urllib2库
程序的起始方法(返回值是公众号文章列表):
defopenUrl():
print("启动爬虫,打开搜狗搜索微信界面")
#加载页面
url='http://weixin.sogou.com/weixin?type=1&s_from=input&query=要爬取的公众号名称'
htmlContentObj=urllib2.urlopen(url)
#将页面转化为文本
html=htmlContentObj.read()
#正则匹配
str=re.findall(r"http://mp.weixin.qq.com/profile.+==",html)
#替换转义符得到可访问的链接地址
tempHref=re.sub(r"&","&",str[0])
returntempHref
根据获取到的文章列表的页的链接地址(注意是文章列表页面的得链接地址,不是文章的地址)将页面读取为文本
#获取页面文本方法 defgetHtmlStr(conurl): #相当于把页面转化为文本 response=urllib2.urlopen(conurl) #读取文本的字符串 htmlStr=response.read() returnhtmlStr
对读取为文本的页面进行分析并利用正则匹配获得公众号里面文章的标题,链接地址等内容得json对象
#文本转换为所需要的json对象
defhtmlToJsonObj(htmlStr):
#正则匹配并得到需要的json字符串
jsonObjstr=re.findall(r"{\"list\":\[.+\]\}",htmlStr)
#字符串转json
jsonObj=json.loads(jsonObjstr[len(jsonObjstr)-1])
returnjsonObj
然后从json对象中取出title,拼接url等(我这里只是获取了链接地址和标题),将两个内容分别存在两个数组,以json对象的方式返回出去(注意拼接url的时候要替换掉转义符(&))
#从json对象中取出所需要的url
defjsonObjToArray(jsonObj):
hrefs=[]
titles=[]
#url中的&在html中是&,故需要替换,下面为正则
patten=re.compile(r"&")
#数组
arr=jsonObj["list"]
#循环添加
foriinrange(len(arr)):
#每次替换字符串
fixHref=re.sub(patten,"&",arr[i]["app_msg_ext_info"]["content_url"])
#添加到数组
titles.append(arr[i]["app_msg_ext_info"]["title"])
hrefs.append("https://mp.weixin.qq.com"+fixHref)
jsons={"hrefs":hrefs,"titles":titles}
returnjsons
#打开浏览器,进行工作
defstart():
tempHref=openUrl()
#获取页面文本
htmlStr=getHtmlStr(tempHref)
#文本转json对象
jsonObj=htmlToJsonObj(htmlStr)
#f返回所需要的url数组
returnjsonObjToArray(jsonObj)
最后通过启动程序的方法启动爬虫并打印爬取到的信息
if__name__=='__main__':
try:
hrefs=start()
count=len(hrefs["hrefs"])
foriinrange(count):
print("标题:"+hrefs["titles"][i].encode("utf-8"))
print("爬取到的路径:"+hrefs["hrefs"][i].encode("utf-8"))
print("------------->>爬取并打印完毕")
exceptExceptionase:
print(str(e))
程序需要导入的包
importurllib2 importjson importre
依次赋值以上代码,填写要爬取的公众号,运行即可
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。