实例一,不需要修改头部直接爬取
import requests
url = "https://item.jd.com/47767508311.html"
try:
r =
requests.get(url)
r.raise_for_status()
r.encoding = r.apparent_encoding
print(r.text[:1000])
except:
print("爬取失败")
实例二,有的网站可能会检测到头部 ’ User-Agent ’ : ’ python-requests/2.11.1’,而识别出当前请求访问的是一个爬虫,因此需要修改头部
import requests
url = "https://www.amazon.cn/dp/B07PJGB6DC?ref_=Oct_DLandingS_D_cc22c87e_61&smid=A26HDXW89ZT98L"
try:
kv = {'user-agent':'Mozilla/5.0'}
r = requests.get(url,headers = kv)
r.raise_for_status()
r.encoding = r.apparent_encoding
print(r.text[:1000])
except:
print("爬取失败")
实例三:搜索引擎关键词提交接口
百度的关键词接口:http://www.baidu.com/s?wd=keyword
360的关键词接口:http://www.so.com/s?q=keyword
百度
import requests
keyword = "Python"
try:
kv = {'wd':keyword}
r = requests.get("http://www.baidu.com/s",params=kv)
print(r.request.url)
r.raise_for_status()
print(len(r.text))
except:
print("爬取失败")
360搜索全代码
import requests
keyword = "Python"
try:
kv = {'q':keyword}
r =requests.get("http://www.so.com/s",params=kv)
print(r.request.url)
r.raise_for_status()
print(len(r.text))
except:
print("爬取失败")
实例四:图片爬取
import requests
import os
url = "https://bkimg.cdn.bcebos.com/pic/4a36acaf2edda3ccbd7b3d6406e93901203f92d3?x-bce-process=image/crop,x_0,y_0,w_1328,h_904/watermark,g_7,image_d2F0ZXIvYmFpa2UxODA=,xp_5,yp_5"
root = "/Users/mac/Downloads//"
path = root + url.split('/')[-1] + ".jpg" # + ".jpg" 使得保存下的文件以jpg格式存储
try:
if not os.path.exists(root):
os.mkdir(root)
if not os.path.exists(path):
r = requests.get(url)
with open(path,'wb') as f:
f.write(r.content)
f.close()
print("文件保存成功")
else:
print("文件已存在")
except:
print("爬取失败")
url是图片地址,root中是想存放在本机的哪个位置
实例五:IP地址查询全代码
import requests
url = "http://m.ip138.com/ip.asp?ip="
try:
r = requests.get(url+'202.204.80.112')
r.raise_for_status()
r.encoding = r.apparent_encoding
print(r.text[-500:])
except:
print("爬取失败")
这个没跑出来,,不知道问题出在哪里,,,