python爬虫学习笔记2:实例学习1

京东商品爬取页面实例

import requests
url = "https://item.jd.com/2967929.html"
try:
    r =requests.get(url)
    r.raise_for_status()
    r.encoding = r.apparent_encoding
    print(r.text[:1000])
except:
    print("爬取失败")

亚马逊商品页面的爬取

网站有时会审查user-agent头,来拒绝爬虫访问,但可以修改user-agent头突破审查

import requests
url = "https://www.amazon.cn/gp/product/B01M8L5Z3Y"
try:
    kv = {'usre-agent':'Mozilla/5.0'} //更改user-agent头
    r=requests.get(url,headers=kv)
    r.encoding=r.apparent_encoding
    print(r.text[1000:2000])
except:
    print("爬取失败")

百度/360搜索关键词提交

//百度搜索全代码
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("爬取失败")

网络图片的爬取和存储

网络图片链接格式:
http://www.example.com/pcture.jpg

import requests
import os
url = "https://i.imgur.com/ciwlCWa.png"
root = r"C:/Users/horyit/Desktop/杂项/"
path = root + url.split('/')[-1]
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("爬取失败")

IP地址归属地的自助查询

IP查询的网址:http://m.ip138.com

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("爬取失败")

猜你喜欢

转载自blog.csdn.net/w0ryitang/article/details/80206235
今日推荐