Python爬虫入门(一)requests库
import requests
import os
url1 = "http://www.baidu.com"
def find_html(url):
try:
r = requests.get(url, timeout=30)
print(r.request.headers)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return "产生异常"
def view_in_browser(url):
try:
kv = {'User-Agent': 'Mozilla/5.0'}
r = requests.get(url, headers=kv)
print(r.request.headers)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return "产生异常"
def search_in_baidu():
kv = {'wd': 'python'}
try:
r = requests.get("http://www.baidu.com/s", params=kv)
print(r.request.url)
r.raise_for_status()
print(len(r.text))
except:
print("爬取失败")
def store_picture(url):
root = "pictures\\"
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("爬取失败")
def search_IP():
kv = {'ip': '202.204.80.112'}
ip_url = "http://www.ip138.com/ips138.asp?"
try:
r = requests.get(ip_url, params=kv)
r.raise_for_status()
r.encoding = r.apparent_encoding
print(r.text)
except:
print("爬取失败")
search_IP()