一、京东商品信息的爬取
这个很简单,直接上代码
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。。用法
第五个事例懒得写了