python爬虫笔记(一):页面的获取(一)

写在前面

有关python爬虫笔记我会一直更新下去,如果您碰巧有什么好的建议,欢迎对我提出,不胜感激。

获取页面

  1. 获取没有禁止爬虫的网页
import requests

url = "https://item.jd.com/4140539.html"

try:
    r = requests.get(url)
    r.raise_for_status()#这个是检测网页响应,如果响应不对,会直接到except
    #print(r.status_code) #去掉前面#可以得到200,说明网页响应正确
    r.encoding = r.apparent_encoding
    print(r.text[:100])
except:
    print("爬去失败")
复制代码
  1. 获取有禁止爬虫(检测headers)的网页
import requests

url = "https://www.amazon.cn/dp/B079FLYB49/ref=cngwdyfloorv2_recs_0/460-7004898-2910845?pf_rd_m=A1AJ19PSB66TGU&pf_rd_s=desktop-2&pf_rd_r=MTJFMQEKZR9180R1YDRV&pf_rd_r=MTJFMQEKZR9180R1YDRV&pf_rd_t=36701&pf_rd_p=7149a3bb-2ee6-4f99-92eb-d87852365f8c&pf_rd_p=7149a3bb-2ee6-4f99-92eb-d87852365f8c&pf_rd_i=desktop"

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:2000])
except:
    print("获取失败")
复制代码

3.百度、360搜索关键词提交

import requests

url = "http://www.baidu.com/s"
keyword = "Python"

try :
    kv = {'wd': keyword}#借口有wd
    r = requests.get(url, params = kv)
    print(r.request.url) #查看浏览器的搜索
    r.raise_for_status()
    print(len(r.text)) #打印搜索网页
except:
    print("获取失败")
复制代码
  1. 网络图片的爬去和储存
import requests
import os

url = "http://image.nationalgeographic.com.cn/2017/1010/20171010012304725.jpg"
root = "E://pics//"
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("获取失败")
    
复制代码
  1. IP地址归属地的自动查询
import requests
import os

url = "http://m.ip138.com/ip.asp?ip="

try :
    r = requests.get(url+'202.204.80.112')
    r.raise_for_status()
    r.recoding = r.apparent_encoding
    print(r.text[-500:])
except:
    print("获取失败")
    
复制代码

转载于:https://juejin.im/post/5a990809f265da237a4c741e

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值