挑战内容
本次挑战中,你需要在 ~/Code/shiyanlou_user.py
文件中编写一个函数 user_info
,user_info
函数接受 1
个参数 user_id
。其中,user_id
用于指定用户 ID。
你需要补充 user_info
函数,使之能解析并返回指定用户 ID 的数据信息。如果指定用户 ID 不存在,则全部返回 None
。
挑战要求
- 代码必须写入
~/Code/shiyanlou_user.py
文件中。 - 函数名必须是
user_info
,如果指定用户 ID 不存在,则全部返回None
。 - 测试时请使用
/home/shiyanlou/anaconda3/bin/python
运行shiyanlou_user.py
,避免出现无相应模块的情况。
区别于示例截图,我们要求返回的数据格式如下:
- 用户名
user_name
:str
类型,例如:huhuhang
- 用户楼层
user_level
:int
类型,例如:179
- 用户加入时间
join_date
:str
类型,例如:2016-06-09
挑战代码答案
标准答案
import requests
from lxml import html
def user_info(user_id):
url = "https://www.shiyanlou.com/users/{}/".format(user_id)
content = requests.get(url)
if content.status_code == 200:
tree = html.fromstring(content.text)
user_name = tree.xpath(
'//div[@class="user-meta"]/span/text()')[0].strip()
user_level = tree.xpath(
'//div[@class="user-meta"]/span/text()')[1].strip()[1:]
join_date = tree.xpath(
'//span[@class="user-join-date"]/text()')[0].strip()[:10]
return user_name, int(user_level), join_date
else:
user_name, user_level, join_date = (None, None, None)
return user_name, user_level, join_date
自己写的
import requests
content = requests.get(url="https://www.lanqiao.cn/users/214893/") # 请求实验楼课程页
if content.status_code == 200:
tree = html.fromstring(content.text)
user_name = tree.xpath( '//div[@class="user-meta"]/span/text()')[0].strip()
user_level = tree.xpath( '//div[@class="user-meta"]/span/text()')[1].strip()[1:]
join_date = tree.xpath( '//span[@class="user-join-date"]/text()')[0].strip()[:10]
print("账户名称"+user_name,"账户等级"+user_level,"注册时间"+join_date)
else :
print("页面解析错误")