Requests库网络爬虫实战(5个实例)
实例1:京东商品页面的爬取
要爬取的页面为:https://item.jd.com/2967929.html
代码如下:
import requests
def getHTMLText(url):
try:
r = requests.get(url, timeout=30)
r.raise_for_status() # 如果状态不是200,引发HTTPError异常
print(r.status_code)
r.encoding = r.apparent_encoding
print(r.encoding)
return r.text
except:
print('爬取失败')
if __name__ == "__main__":
url = "https://item.jd.com/2967929.html"
print(getHTMLText(url)[:1000])
结果为:
200
ascii
<script>window.location.href='https://passport.jd.com/new/login.aspx?ReturnUrl=http%3A%2F%2Fitem.jd.com%2F2967929.html'</script>
需要登入京东,待解决的问题
实例2:亚马逊商品页面的爬取
第一次需要Marketplace APIs ,需要修改r.request.headers
import requests
def getHTMLText(url):
try:
kv = {'User-Agent':'Mozilla/5.0'}
r = requests.get(url, headers=kv, timeout=30)
# print(r.request.headers)
r.raise_for_status() # 如果状态不是200,引发HTTPError异常
r.encoding = r.apparent_encoding
return r.text
except:
print('爬取失败')
if __name__ == "__main__":
url = "https://www.amazon.cn/gp/product/B01M8L5Z3Y"
print(getHTMLText(url))
实例3:百度/360搜索关键字提交
搜索引|擎关键词提交接口:http://www.baidu.com/s?wd=keyword
import requests
def getHTMLText(url):
try:
kv = {'wd': 'Python'}
r = requests.get(url, params=kv, timeout=30)
print(r.status_code)
r.raise_for_status() # 如果状态不是200,引发HTTPError异常
r.encoding = r.apparent_encoding
return r.text
except:
print('爬取失败')
if __name__ == "__main__":
url = "http://www.baidu.com/s?wd=keyword"
print(len(getHTMLText(url)))
这里的url应该为"http://www.baidu.com/s?“或"http://www.baidu.com/s”
实例4:网络图片的爬取和存储
图片地址:https://edu-image.nosdn.127.net/3321D6673EB82C94D08E1B80E8344166.jpg
这个代码请动手敲一下,第一次爬图片QAQ
import requests
import os
def getHTMLText(url):
try:
r = requests.get(url, timeout=30)
print(r.status_code)
r.raise_for_status() # 如果状态不是200,引发HTTPError异常
r.encoding = r.apparent_encoding
return r
except:
print('爬取失败')
if __name__ == "__main__":
url = "https://edu-image.nosdn.127.net/3321D6673EB82C94D08E1B80E8344166.jpg"
root = "D://University_Study//2021毕设//2020毕业设计//Code//教师授课视频//第一周/"
path = root + url.split('/')[-1] # 在root新建3321D6673EB82C94D08E1B80E8344166.jpg
if not os.path.exists(root):
os.mkdir(root)
if not os.path.exists(path):
r = getHTMLText(url)
with open(path, 'wb') as f:
f.write(r.content)
f.close()
print('文件保存成功')
else:
print('文件已存在')
实例5:IP地址归属地的自动查询
https://m.ip138.com/iplookup.asp?ip=ipaddress
爬取失败,可能需要校园网或者需要登陆
小结
MOOC第一周网络爬虫之规则完毕