路飞学城—python爬虫实战密训-—第1章(作业)

一: 学习心得,体会

  1. 感觉跟着视频做的汽车之家,和抽屉网站登录的爬虫没有那么难。但做github登录并获取信息的,就觉得不太容易了,登录操作挺简单,和抽屉例子差不多,但获取个人信息部分就感觉有点麻烦了,主要是个人信息部分在哪里找不到,后来还是看的群里老师分享的优秀作业,需要在登录后获取名字,拼接网址,转换到个人主页部分,再来获取个人信息

二:

作业题目: 爬虫实战密训营作业(一)

作业需求:

1. 基于requests实现自动登录GitHub并获取个人信息
import  requests
from bs4 import BeautifulSoup
#1获取token和cookie
r1 = requests.get(
    url = "https://github.com/login"
)
s1 = BeautifulSoup(r1.text,'html.parser')
token = s1.find(name='input',attrs = {'name':'authenticity_token'}).get('value')
cookie1 = r1.cookies.get_dict()
#2 进行登录并返回登录信息并获取用户名
r2 = requests.post(
    url="https://github.com/session",
    data = {
        'commit':'Sign in',
        'utf8':'',
        'authenticity_token':token,
        'login':'[email protected]',
        'password':'qq183443595'
    },
   cookies=cookie1
)
s2 = BeautifulSoup(r2.text, 'html.parser')
#获取登录错误信息
error_text = s2.find(name = 'div',attrs={'class':'flash flash-full flash-error'})
# 账号密码错误时返回错误信息,登录成功进行提示
if  error_text:
    print(error_text.text.strip())
else:
    print ("登录成功!!")
# 这一步获取用户名之后才能有第三步,在个人主页上获取个人信息
name = s2.find(name='meta', attrs={'name': "octolytics-actor-login"}).get('content')
# 3 获取用户信息
r3 = requests.get(
    url='https://github.com/%s' % name,
    cookies=cookie1
)
s3 = BeautifulSoup(r3.text, 'html.parser')
#获取用户的name,nickname,repositories,activity
p_name = s3.find(name='span', attrs={'class': 'p-name'})
p_nickname = s3.find(name='span', attrs={'class': 'p-nickname'})
p_note = s3.find(name='div', attrs={'class': 'p-note user-profile-bio'})
repositories = s3.find(name = 'div',attrs={'class':'blankslate mb-4'})
activity = s3.find(name='div', attrs={'class': 'text-center text-gray pt-3'})
#进行输出
print("p_nickname:"+p_nickname.text)
print ("p_name: "+p_name.text)
print ("p_note: "+p_note.text)
print ("repositories: "+repositories.text.strip())
print("activity: "+activity.text.strip())

猜你喜欢

转载自www.cnblogs.com/andydong/p/9275676.html
今日推荐