中国大学MOOC·Python网络爬虫与信息提取(二)——五个实例分析
2017-09-04 21:11
633 查看
一、京东商品信息的爬取
这个很简单,直接上代码import requests url='https://item.jd.com/5181380.html' try: r = requests.get(url) r.raise_for_status() r.enconding = r.apparent_encoding print(r.text[:1000]) except: print("抓取失败")
注意爬虫框架的使用
二、亚马逊商品的爬取(涉及隐藏爬虫访问)
import requests url = 'https://www.amazon.cn/dp/B073FGTZSR/ref=gbph_img_m-6_f31a_6eb7c6e6?smid=A1AJ19PSB66TGU&pf_rd_p=1811740a-8637-4216-80f7-f515ea8bf31a&pf_rd_s=merchandised-search-6&pf_rd_t=101&pf_rd_i=1907896071&pf_rd_m=A1AJ19PSB66TGU&pf_rd_r=VA13APM2DPA9W21QTRZV' def text(url): try: kv={'user-agent':'Mozilla/5.0'} r = requests.get(url,headers=kv) r.raise_for_status()#如果状态不是200,引发HTTPError异常 r.encoding = r.apparent_encoding print (r.status_code) except: print('产生异常')
这里使用的是直接采取 requests.get.(url,headers==)的方法
三、百度/360搜索关键词的提交
1.首先需要清楚百度/360的搜索接口其实就是
那么我们需要做的就是吧wd=keyword 替换成wd=我们要搜索的内容
代码如下:
>>> import requests >>> kv = {'wd':'pyhthon'} >>> r = requests.get('http://www.baidu.com/s',params=kv) >>> r.status_code 200 >>> r.request.url 'http://www.baidu.com/s?wd=pyhthon' >>> len(r.text) 425274
这里使用到了参数用法中的params用法,主要的作用是将即将访问的url链接进行添加内容并且直接生成?+添加内容
这里也可以直接简单的生成:
>>> import requests >>>r = requests.get('http://www.baidu.com/s?wd=pyhthon') >>> len(r.text) 425274
四、网络图片的爬取
先上代码:
import requests import os root = 'D:/ABC/'#创建一个根目录 url = 'http://img0.dili360.com/rw9/ga/M00/3C/72/wKgBy1XukgeAVHNfACe6Q6XxwU4840.tub.jpg' path=root+url.split('/')[-1] #SPLIT是一个命令读取指定文件,以 1000 行大小写在一组输出文件上。功能是返回一个下标从零开始的一维数组,即[-1]就是返回斜杠后面的JPG所属的文件 try: if not os.path.exists(root):#如果根目录不存在就创建一个 os.mkdir(root) if not os.path.exists(path):#如果路径不存在即没有图片就开始抓取 r = requests.get('http://img0.dili360.com/rw9/ga/M00/3C/72/wKgBy1XukgeAVHNfACe6Q6XxwU4840.tub.jpg') with open(path,'wb') as f: #这里重点需要掌握with..as的用法 下文有链接 #把抓取的文件写入路径 #传入标识符'w'或者'wb'表示写文本文件或写二进制文件: f.write(r.content) f.close() print("succeed") else: print('the file existed') except: print('fail')
添加内容:关于OS库,写入写出文件,as with的用法:
http://www.iplaypy.com/module/os.html网络上对于OS库的详细内容介绍
http://www.runoob.com/python3/python3-file-methods.html
http://www.iplaypy.com/sys/open.html
Python3 File(文件) 方法
http://www.cnblogs.com/itcomputer/articles/4601411.html
with。。。as。。用法
第五个事例懒得写了
相关文章推荐
- Python网络爬虫与信息提取-中国大学MOOC
- Python网络爬虫与信息提取(中国大学mooc)
- Python网络爬虫与信息提取-Day10-(实例)中国大学排名定向爬虫
- 中国大学MOOC·Python网络爬虫与信息提取(一)
- 【MOOC】Python网络爬虫与信息提取-北京理工大学-part 2
- Python网络爬虫与信息提取(实例讲解)
- Python网络爬虫与信息提取-Day14-(实例)股票数据定向爬虫
- MOOC-Python网络爬虫与信息提取-第二周 BeautifulSoup库入门与信息提取方法
- 【MOOC】Python网络爬虫与信息提取-北京理工大学-part 1
- 【MOOC】Python网络爬虫与信息提取-北京理工大学-part 3
- 【MOOC】Python网络爬虫与信息提取-北京理工大学-part 4
- Python网络爬虫与信息提取-Day5-Requests库网络爬取实战
- python——博客园首页信息提取与分析
- Python 网络爬虫与信息获取(二)—— 页面内容提取
- Python网络爬虫与信息提取-Day9-信息标记与提取方法
- Python网络爬虫与信息提取(一)
- Python网络爬虫与信息提取(一):网络爬虫之规则
- Python网络爬虫与信息提取-Day3-requests库(3)
- Python网络爬虫与信息提取(三):网络爬虫之实战
- python网络爬虫与信息采取之解析网页实例---oJ期末成绩排名