下载requests库,命令行pip install requests即可安装。命令行爬取京东实例:
>>> import requests
>>> r=requests.get("https://item.jd.com/3133813.html")
>>> r.status_code
200
>>> r.encoding
'gbk'
>>> r.text[:1000]
'<!-- shouji -->\n<!DOCTYPE HTML>\n<html lang="zh-CN">\n<head>\n <meta http-equiv="Content-Type" content="text/html; charset=gbk" />\n <title>【AppleiPhone7】Apple iPhone 7 (A1660) 32G 玫瑰金色 移动联通电信4G手机【行情 报价 价格 评测】-京东</title>\n <meta name="keywords" content="AppleiPhone7,AppleiPhone7,AppleiPhone7报价,AppleiPhone7报价"/>\n <meta name="description" content="【AppleiPhone7】京东JD.COM提供AppleiPhone7正品行货,并包括AppleiPhone7网购指南,以及AppleiPhone7图片、iPhone7参数、iPhone7评论、iPhone7心得、iPhone7技巧等信息,网购AppleiPhone7上京东,放心又轻松" />\n <meta name="format-detection" content="telephone=no">\n <meta http-equiv="mobile-agent" content="format=xhtml; url=//item.m.jd.com/product/3133813.html">\n <meta http-equiv="mobile-agent" content="format=html5; url=//item.m.jd.com/product/3133813.html">\n <meta http-equiv="X-UA-Compatible" content="IE=Edge">\n <link rel="canonical" href="//item.jd.com/3133813.html"/>\n <link rel="dns-prefetch" href="//misc.360buyimg.com"/>\n <link rel="dns-prefetch" href="//static.360buyi'
>>>
其中status_code返回200表示链接成功
import requests
url="www.baidu.com"
try:
r=requests.get(url)
r.raise_for_status()
r.encoding=r.apparent_encoding
print(r.text[:1000])
except:
print("爬取失败")