了解了爬虫和网络请求之后,就可以开始正式了解Python中爬虫相关的模块了。很多爬虫相关的书籍,一般开头都会讲到urllib模块,等你看完本书再告诉你,urllib模块使用起来比较复杂,一般用不到。确实,urllib是一个比较老的模块,封装的爬虫方法也比较复杂。所以可以直接启动requests模块。Requests模块的作用是模拟浏览器发送请求。它是Python中基于网络请求的原生模块。它不仅功能强大,而且使用起来也比较简单!模块的安装可以直接通过pip安装。pipinstallrequests使用起来也非常简单。分三步指定url,也就是说你要爬取的网站地址发送请求,请求分为GET/POST/PUT/获取响应数据是不是很简单删除等等?废话不多说,举个简单的例子,比如我需要爬取百度首页GET请求#importmoduleimportrequestsurl='https://www.baidu.com'#sendgetrequestresponse=requests.get(url)#获取网页源代码baidu_html=response.text#持久化(保存)获取的数据withopen('baidu.html','w',encoding='utf-8')asf:f.write(baidu_html)执行后,同级目录下会有一个baidu.html文件。以上就是一个最基本的使用requests发送get请求的例子。同理,如果你发送POST/PUT/HEAD等其他请求requests.post(url)requests.delete(url)requests.put(url)...发送请求时,大部分时候会携带一些参数。比如我们搜索的时候,发送的GET请求会携带搜索内容。比如我在百度上搜索python,url是https://www.baidu.com/s?wd=python为了让爬虫程序更加灵活,就必须将搜索的内容分开。可以通过构造字典参数发送GET请求importrequests#输入搜索关键字wd=input('请输入您要搜索的内容:\n')url='https://www.baidu.com/s?'#构建get请求的搜索参数url_param={'wd':wd}#为了防止爬虫被拦截,添加请求的UA头={'user-agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/83.0.4103.106Safari/537.36'}#发送GET请求response=requests.get(url,params=url_param,headers=header)#获取网页源代码wd_html=response.text#写入文件,持久化操作withopen('wd.html','w',encoding='utf-8')asf:f.write(wd_html)具体GET用法如下#url访问地址#params携带参数#**kwargs其他参数,如请求头、cookie、代理等defget(url,params=None,**kwargs):POST请求使用httpbin网站,用于测试httpbin是一个网站可以测试HTTP请求和响应,支持多种请求方式1.以表单形式提交参数,只需要将请求参数构造成字典,传递给the数据参数。importrequestsurl='http://httpbin.org/post'params={'name':'公众号:Python极客专栏','language':'python'}response=requests.post(url,data=params)print(response.json())执行结果:{'args':{},'data':'','files':{},'form':{'language':'python','name':'公众号:Python极客专栏'},'headers':{'Accept':'*/*','Accept-Encoding':'gzip,deflate','Content-Length':'99','Content-Type':'application/x-www-form-urlencoded','Host':'httpbin.org','User-Agent':'python-requests/2.22.0','X-Amzn-Trace-id':'Root=1-5fef5112-65ad78d4706c58475905fef2'},'json':None,'origin':'','url':'http://httpbin.org/post'}2,作为字符串提交参数以json.dumps的形式将字典转换成字符串importrequestsimportjsonheader={'user-agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/83.0.4103.106Safari/537.36'}url='http://httpbin.org/post'params={'name':'Tom','hobby':['music','game']}#通过json.dumps将字典格式化成json字符串response=requests.post(url,json=json.dumps(params),headers=header)print(response.json())执行结果:{'args':{},'data':'"{\\"name\\":\\"Tom\\",\\"hobby\\":[\\"music\\",\\"game\\"]}"','files':{},'form':{},'headers':{'Accept':'*/*','Accept-编码':'gzip,deflate','Content-Length':'55','Content-Type':'application/json','Host':'httpbin.org','User-Agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/83.0.4103.106Safari/537.36',#请求中添加的headers也可以在这里看到'X-Amzn-Trace-Id':'Root=1-5fef583e-5224201d08e2ff396416e822'},'json':'{"name":"Tom","hobby":["music","game"]}','origin':'','url':'http://httpbin.org/post'}3.使用post请求提交文件(多部分形式)importrequestsimportjsonheader={'user-agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/83.0.4103.106Safari/537.36'}url='http://httpbin.org/post'#读取baidu.html文件,'rb':读取二进制形式的文件={'file':open('baidu.html','rb')}#post表单传入文件fileresponse=requests.post(url,files=files)print(response.json())执行结果:{'args':{},'data':'','files':{'file':'.....这里省略了HTML内容...'},'form':{},'headers':{'Accept':'*/*','Accept-Encoding':'gzip,deflate','Content-Length':'2732','Content-Type':'multipart/form-data;boundary=1ba2b1406c4a4fe89c1846dc6398dae5','Host':'httpbin.org','User-Agent':'python-requests/2.22.0','X-Amzn-Trace-Id':'Root=1-5fef58f8-68f9fb2246eb190f06092ffb'},'json':None,'origin':'','url':'http://httpbin.org/post'}响应处理通过GET/POST等请求获取服务器的响应,其中上面的示例响应是如何获取更多信息?importrequestheaders={'referer':'https://www.baidu.com','user-agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/83.0.4103.106Safari/537.36'}url='http://httpbin.org/post'#读取baidu.html文件,'rb':读取二进制形式的文件={'file':open('baidu.html','rb')}#post形式传递给文件fileresponse=requests.post(url,files=files,headers=headers,cookies={'test':'abcdefg'})#响应处理#指定编码response.encoding='utf-8'print(response.url)#请求的urlprint(response.encoding)#请求的编码,print(response.status_code)#状态码print(response.content)#二进制形式的响应内容(保存文件、图片、音频等)print(response.text)#文本形式的响应内容print(response.json())#JSON形式的响应内容print(response.headers)#响应头信息print(response.request.headers)#请求头信息print(response.request.headers['referer'])#请求头对应属性内容print(response.cookies)#cookie信息,返回cookie对象print(response.cookies.items())输出结果如下图
