Python爬虫学习日志(3)

爬虫实例

1.爬取京东商品页面

  1. 源代码
import requests
url = "https://item.jd.com/7652029.html"
try:
    r = requests.get(url)
    #print(r.status_code)
    r.raise_for_status()
    r.encoding = r.apparent_encoding
    print(r.text[:1000])
except:
    print("爬取失败")

2.爬取亚马逊商品页面

  1. 源代码

模拟浏览器

import requests
url = "https://www.amazon.cn/dp/B07NQCSZHQ"
try:
    kv = {'user-agent':'Mozilla/5.0'} #Mozilla/5.0 是浏览器标识
    r = requests.get(url, headers= kv)
    # print(r.status_code)
    r.raise_for_status()
    r.encoding = r.apparent_encoding
    print(r.text[:1000])
except:
    print("爬取失败")

3.360/百度搜索关键词提交

  • 360的关键词接口:
    http://www.so.com/s?q=keyword
  • 百度的关键词接口:
    http://www.baidu.com/s?wd=keyword
  1. 源代码
    360搜索关键字(Python)
import requests
keyword = "Python"
kv = {'q':keyword}
try:
    r = requests.get("http://www.so.com/s", params= kv)
    print(r.request.url)
    r.raise_for_status()
    print(len(r.text))
except:
    print("爬取失败")
  1. 输出结果
https://www.so.com/s?q=Python
347073
  1. 百度搜索关键字
    百度搜索关键字时,会跳转到百度安全认证,认证通过后,才可以展示搜索结果。

4.网络图片的爬取和存储

  1. 源代码
import requests
import os
url = "https://c-ssl.duitang.com/uploads/item/201208/30/20120830173930_PBfJE.thumb.700_0.jpeg"
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("爬取失败")

5.IP地址归属地的自动查询

IP查询网站:www.ip138.com
http://m.ip138.com/ip.asp?ip=ipaddress

  1. 源代码
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("爬取失败")
  1. 输出结果
value="查询" class="form-btn" />
					</form>
				</div>
				<div class="query-hd">ip138.com IP查询(搜索IP地址的地理位置)</div>
				<h1 class="query">您查询的IP:202.204.80.112</h1><p class="result">本站主数据:北京市海淀区 北京理工大学 教育网</p><p class="result">参考数据一:北京市 北京理工大学</p>

			</div>
		</div>

		<div class="footer">
			<a href="http://www.miitbeian.gov.cn/" rel="nofollow" target="_blank">沪ICP备10013467-1</a>
		</div>
	</div>

	<script type="text/javascript" src="/script/common.js"></script></body>
</html>

北京理工大学主页

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值