requests库的七个主要方法: requests.request() 构造一个请求,支撑以下各方法的基础方法 requests.get() 获取HTML网页的主要方法,对应于HTTP的GET requests.head() 获取HTML网页头信息的方法,对应于HTTP的HEAD requests.post() 向HTML网页提交POST请求的方法,对应于HTTP的POST requests.put() 向HTML网页提交PUT请求的方法,对应于HTTP的PUT requests.patch() 向HTML网页提交局部修改请求,对应于HTTP的PATCH requests.delete() 向HTML页面提交删除请求,对应于HTTP的DELETE
Response 对象的属性: r.status_code HTTP请求的返回状态,200表示连接成功,404表示失败 r.text HTTP响应内容的字符串形式,即,url对应的页面内容 r.encoding 从HTTP header中猜测的响应内容编码方式 r.apparent_encoding 从内容中分析出的响应内容编码方式(备选编码方式) r.content HTTP响应内容的二进制形式 r.encoding:如果header中不存在charset,则认为编码为ISO‐8859‐1 r.text根据r.encoding显示网页内容 r.apparent_encoding:根据网页内容分析出的编码方式可以看作是r.encoding的备选
url='http://img.pconline.com.cn/images/upload/upc/tx/itbbs/1603/12/c0/19116451_1457712534499_mthumb.jpg' root='D:\p' path=root+"\\"+url.split('/')[-1] print(path) try: if not os.path.exists(root): os.mkdir(root) if not os.path.exists(path): r=requests.get(url) print(r.status_code) with open(path,'wb') as f: f.write(r.content) f.close() else: print('文件已经存在') except: print('爬取失败')
import requests def getHTMLText(url): try: r=requests.get(url,timeout=30) r.raise_for_status() r.encoding=r.apparent_encoding return r.text except: return "产生异常" if _name_="_main_": url="http://www.baidu.com" print(getHTMLText(url))
**kwargs: 控制访问的参数,均为可选项 params : 字典或字节序列,作为参数增加到url中: data : 字典、字节序列或文件对象,作为Request的内容 json : JSON格式的数据,作为Request的内容 headers : 字典,HTTP定制头 cookies : 字典或CookieJar,Request中的cookie auth : 元组,支持HTTP认证功能 files : 字典类型,传输文件 timeout : 设定超时时间,秒为单位 proxies : 字典类型,设定访问代理服务器,可以增加登录认证 allow_redirects : True/False,默认为True,重定向开关 stream : True/False,默认为True,获取内容立即下载开关 verify : True/False,默认为True,认证SSL证书开关 cert : 本地SSL证书路径
Beautiful Soup库
def a(url): try: r=requests.get(url) r.raise_for_status() r.encoding=r.apparent_encoding return r.text except: return '' def b(list,html): soup=BeautifulSoup(html,'html.parser') for tr in soup.find('tbody').children: if isinstance(tr,bs4.element.Tag): tds=tr.find_all('td') list.append([tds[0].string,tds[1].string,tds[2].string]) def c(list,num): t='{0:<10}\t{1:{3}<10}\t{2:{3}<10}' print('{0:<10}{1:<12}\t\t{2:<12}'.format('学校','学校名称','地区',chr(12288))) for i in range(num): u=list[i] print(t.format(u[0],u[1],u[2],chr(12288))) def main(): l=[] url='http://www.zuihaodaxue.com/zuihaodaxuepaiming2016.html' html=a(url) b(l,html) c(l,20) main()