Python爬虫学习系列2

几个爬虫实例

1. 爬取京东商品信息

爬取的网页网址:item.jd.com/100011351676.html

import requests
url = "https://item.jd.com/100011351676.html"
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("Failed")

2. 百度/360搜索关键词提交

百度:www.baidu.com
360搜索:www.so.com
搜索关键词提交接口
百度:www.baidu.com/s?wd=keyword
360搜索:www.so.com/s?q=keyword

百度

import requests
# 百度搜索“Python”关键词
kv1 = {'wd':'Python'}
kv2 = {'user-agent':'Mozilla/5.0'}
url1 = "https://www.baidu.com/s"
try:
    r1 = requests.get(url1, params=kv1, headers=kv2)
    r1.raise_for_status()
    r1.encoding = r1.apparent_encoding
    print(len(r1.text))
except:
    print("Failed")
# 2020/05/28测试时发现百度有安全验证,无法爬取相关信息

360搜索

import requests
# 360搜索“Python”关键词
kv1 = {'q':'Python'}
kv2 = {'user-agent':'Mozilla/5.0'}
url1 = "https://www.so.com/s"
try:
    r1 = requests.get(url1, params=kv1, headers=kv2)
    r1.raise_for_status()
    r1.encoding = r1.apparent_encoding
    print(len(r1.text))
except:
    print("Failed")
# 2020/05/28 测试时是可以提取相关信息的

3. 爬取图片

图片链接的格式

http://www.example.com/picture.jpg
例如:国家地理:www.nationalgeographic.com.cn
选取一个图片的Web页面:
http://www.ngchina.com.cn/photography/picture_story/6297.html
其中的图片地址:
http://image.ngchina.com.cn/2020/0525/20200525045005162.jpg

爬取图片并保存

import requests
import os
url = "http://image.ngchina.com.cn/2020/0525/20200525045005162.jpg"
root = "D://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("Successfully saved files !")
    else:
        print("files have already existed !")    
except:
    print("Failed")

4. 自动查询IP地址

查询ip所使用的网站:www.ip138.com
查询ip时网站所显示的字段:https://www.ip138.com/iplookup.asp?ip=ipaddress
或者 https://m.ip138.com/iplookup.asp?ip=ipaddress
查询时的代码:

import requests
url = "https://m.ip138.com/iplookup.asp?ip="
ipaddress = '202.204.80.112' #北理工的教育网址
kv = {'user-agent':'Mozilla/5.0'}
try:
    r = requests.get(url+ipaddress, headers=kv)
    r.raise_for_status()
    r.encoding = r.apparent_encoding
    print(r.text[1000:2000])
except:
    print("Failed")

看完随手点个赞吧!可怜我到现在一个成就都没达成

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值