在上个爬虫中我们通过本地的四六级考生信息获取对应的成绩,这次我们主要是获取知乎用户的粉丝的相关信息存储在数据库中,数据库依然采用的是mysql数据库。
这次爬取的是知乎上“余弦”的粉丝,我们在这个之前会先模拟登陆,然后研究内容的获取。
模拟登陆不多说了,和登录科大信息门户的类似,这边直接附上代码
#获取_xsrf的值
def collect(self):
reponse=urllib.request.urlopen('https://www.zhihu.com/#signin')
data=reponse.read().decode()
soup=BeautifulSoup(data,'html.parser')
link=soup.find_all('input')
link=str(link[0])
link=link[41:73]
return link
#post相关的数据
def post(self):
cj = http.cookiejar.CookieJar()
pro = urllib.request.HTTPCookieProcessor(cj)
opener = urllib.request.build_opener(pro)
urllib.request.install_opener(opener)
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.71 Safari/537.36r)'
header = {'User-Agent': user_agent}
postdata = urllib.parse.urlencode({
'_xsrf':self.collect(),
'password':'a12345',
'phone_num':'15598438801'
})
postdata = postdata.encode('utf-8')
url = 'https://www.zhihu.com/login/phone_num'
req = urllib.request.Request(url,postdata,headers=header)
result=opener.open(req)
知乎账号随便用,开始怕被封,淘宝买的,3毛钱,不过现在知乎好像添加了验证码,登录不是很容易,你可以把验证码加载到本地,手工验证,至于是选倒字的,我也无能为力了。
工作URL:https://www.zhihu.com/people/evilcos/followers
按照常规方法,我们发现我们并不能在response.read()里找到我们想要的数据,这是因为知乎是动态加载的,他的数据都存在json文件里,我们要做的就是获得json文件里的数据,并解析他们。
在firebug下面,我们刷新页面,看页面加载了那些内容。
幸福总是在不经意间来临,如果第一次看不到,那就点下一页,总会出现的。
我们观察这些json的URL发现URL是有规律的,
www.zhihu.com/api/v4/members/evilcos/followers?include=data%5B*%5D.answer_count%2Carticles_count%2Cgender%2Cfollower_count%2Cis_followed%2Cis_following%2Cbadge%5B%3F(type%3Dbest_answerer)%5D.topics&offset=0&limit=20
offset代表开始的位置,limit代表依次加载的数量
我们可以得到前一个或者后一个json的URL,而且还可以判断是不是最后一个URL,是不是很贴心。下面就是获取json信息,存储在数据库的代码。
conn=mysql.connector.connect(user='root',password='',database='spider')
cursor=conn.cursor()
m=1
rr=requests.get('https://www.zhihu.com/api/v4/members/evilcos/followers?include=data%5B*%5D.answer_count%2Carticles_count%2Cgender%2Cfollower_count%2Cis_followed%2Cis_following%2Cbadge%5B%3F(type%3Dbest_answerer)%5D.topics&offset=0&limit=20',cookies=cj,headers=header).json()
try:
while not rr['paging']['is_end']:
for user in rr['data']:
name=user['name']
headline=user['headline']
user_url=urllib.parse.urljoin('https://www.zhihu.com/people/',user['id'])
answer_count=user['answer_count']
articles_count=user['articles_count']
follower_count=user['follower_count']
user_id=user['id']
user_avatar_url=user['avatar_url']
cursor.execute('insert ignore into zhihu_user(id, user_name,user_headline,user_url,user_answer_count,user_articles_count,user_follower_count,user_id) values(%s,%s,%s,%s,%s,%s,%s,%s)',[m,name,headline,user_url,answer_count,articles_count,follower_count,user_id])
conn.commit()
print('已经插入'+str(m)+'条')
m=m+1
url=rr['paging']['next']
rr=requests.get(url,cookies=cj,headers=header).json()
cursor.close()
conn.close()
except Exception as e:
print('error:',e)
现在就可以运行在数据库内看爬取到的信息了。
GitHub地址:https://github.com/wanghaoying/Python/tree/master/scray/zhihu_user/zhihu_user1.0