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")