python爬去新浪微博_python 爬取新浪微博信息

新浪微博爬取的话需要设计到登录,这里我没有模拟登录,而是使用cookie进行爬取。

获取cookie:

wKioL1mJML3j2zx3AADTqQSZXG0258.png-wh_500x0-wm_3-wmp_4-s_1312038099.png

wKiom1mJMNWR-NW3AAXbBOQBObw578.png-wh_500x0-wm_3-wmp_4-s_3181523793.png

代码:#-*-coding:utf8-*-

from bs4 import BeautifulSoup

import requests

import time

import os

import sys

import random

reload(sys)

sys.setdefaultencoding('utf-8')

user_id = 用户id

cookie = {"Cookie": "_T_WM=f3a2assae4335dfdf38fdc7a25a88; SCF=ApMI3mluv9yH6yKz4i7-HMlHojzPtQULc5G0xlrri-NeO3Xn1FRWI5W1HElZWG1bMkX4mV_OhKDtNV2IhxJQGLs.; SUB=_2A250jET_DeRhGeNN7FsX9CrIzzqIHXVXj2y3rDV6PUJbkdBeLUrnkW1AtfoOlrd_kyd1Izu7Q1uKaFvRDQ..; SUHB=0k1ySJSrJVBDGD; SSOLoginState=1502098607"}

for page in range(100):

url = 'https://weibo.cn/573550093?page=%d' % page

response = requests.get(url, cookies = cookie)

html = response.text

soup = BeautifulSoup(html, 'lxml')

username = soup.title.string

cttlist = []

for ctt in soup.find_all('span',class_="ctt"):

cttlist.append(ctt.get_text())

ctlist = []

for ct in soup.find_all('span',class_="ct"):

ctlist.append(ct.get_text())

if page == 0:

print "微博用户资料:" + cttlist[0]

print "微博用户个性签名:" + cttlist[1]

print "用户的微博动态:\n"

imgurllist = []

for img in soup.find_all('a'):

if img.find('img') is not None :

if 'http://tva3.' not in img.find('img')['src'] and 'https://h5' not in img.find('img')['src']:

imgurllist.append(img.find('img')['src'])

#imgname = soup.title.string + '_' + str(page) + str(time.time()) +str(random.randrange(0, 1000, 3)) +'.jpg'

if not os.path.exists(str(soup.title.string)):

os.mkdir(str(soup.title.string))

#imgname ='./'+ str(soup.title.string) + '/'+ soup.title.string + '_' + str(time.time()) +'.jpg'

for imgurl in imgurllist:

imgname = './'+ str(soup.title.string) + '/'+soup.title.string + '_' + str(page) + str(time.time()) +str(random.randrange(0, 1000, 3)) +'.jpg'

response = requests.get('%s' % imgurl)

dirw = str(soup.title.string)

open(imgname, 'wb').write(response.content)

time.sleep(1.5)

try:

for i in range(len(ctlist)):

print cttlist[2+i]

print ctlist[i]

print "\n"

except:

for i in range(len(ctlist)):

print cttlist[i]

print ctlist[i]

print "\n"

if "下页" not in soup.select('div[id="pagelist"]')[0].get_text():

break

time.sleep(random.randint(1,3))

效果展示:

wKioL1mJQLTy1ZkmAAIULD7liww937.png-wh_500x0-wm_3-wmp_4-s_2394453633.png

wKioL1mJQvOA6i52AA2OaKf9Pr0595.png-wh_500x0-wm_3-wmp_4-s_2720288567.png

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值