Python爬虫笔记

第一单元  request库的使用

初级入门只需掌握requests.get()\\\  lrequests.head()两种方法。

1、requests.get():

r=requests.get(url)    r中包含服务器资源的Response对象,get构造一个向服务器请求资源的Request对象。

(1)response对象的属性

 

Python爬虫笔记

 

#爬取网页的通用框架
import requests
def getHTML.Text(url):
    try:
        r=requests.get(url,timeout=30)
        r.raise_for_status()    #如果状态不是200,引发HTTPError异常
        r.encoding=r.apprent_encoding
        return r.text
    except:
        return"产生异常"
if __name__=="__main__":
    url="http://www.baidu.com"
    print(getHTMLText(url))

'''
r=requests.get("http://www.baidu.com")
l= r.status_code
print(l)
r.encoding='utf-8'   #转换成标准
print(r.text)
'''

Python爬虫笔记

2、request.head()用法

Python爬虫笔记

 

 

3、HTTP协议  超文本传输协议

HTTP URL 可以类比为文件系统里的路径,只不过对应的是整个网络。

Python爬虫笔记

 

Python爬虫笔记

 

 

Python爬虫笔记

  

#爬取京东某商品页面
import requests
url="https://item.jd.com/7629588.html"
r=requests.get(url)
r.enconding=r.apparent_encoding
print(r.text[:1000])
import requests
url="https://www.amazon.cn/dp/B00OB3SNMY/ref=cngwdyfloorv2_recs_0?pf_rd_p=d2aa3428-dc2b-4cfe-bca6-5e3a33f2342e&pf_rd_s=desktop-2&pf_rd_t=36701&pf_rd_i=desktop&pf_rd_m=A1AJ19PSB66TGU&pf_rd_r=B6JN19ZJF1PYZ6S9Y8M5&pf_rd_r=B6JN19ZJF1PYZ6S9Y8M5&pf_rd_p=d2aa3428-dc2b-4cfe-bca6-5e3a33f2342e"
kv={'user-agent':'Mozilla/5.0'}     #字典
r=requests.get(url,headers=kv)       #设置Header参数假冒正常请求
r.enconding='utf-8'
print(r.text[:1000])
#百度关键词查找   360的网址是http://www.so.com/s
import requests
url="http://www.baidu.com/s"
keyword="Python"
kv={'wd':keyword}
r=requests.get(url,params=kv)
r.enconding='utf-8'
print(r.text)
#ip地址查询
import requests
url="http://m.ip138.com/ip.asp?ip="

r=requests.get(url+'202.204.80.112')
r.enconding='utf-8'
print(r.text[-500:])