Python网络爬虫与信息提取
requests库
try:
r = requests.get(url,timeout=30)
r.raise_for_status()#没有200将产生异常
r.encoding = r.apparent_encoding #解码方式的获取和解码
return r.text
except:
return "异常"
params参数,在url后面拼接数据
r = resquesrs.get("www.../s", params = {'ww':'112'})
# www.../s?ww=112
import requests
keyword = "Pyrthon"
try:
kv = {'q':keyword}
r=requests.get("http://www.so.com/s",params=kv)
print(r.request.url)
r.raise_for_status()
print(len(r.text))
except:
print("失败")
r.content 返回数据的二进制形式
爬取图片
import requests
import os
url = 'http://.../sss.jpg'
root = "F://pic//"
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("down load success")
else:
print("file exist")
escept:
print("unsuccess")
Robots协议
公告作用,自觉遵守。
https://www.baidu.com/robots.txt
User-agent: Baiduspider
Disallow: /baidu
Disallow: /s?
Disallow: /ulink?
Disallow: /link?
Disallow: /home/news/data/
Disallow: /bh
遵循方式:
自动读取robots.txt,确保自身spider爬取的域allow。
Beautiful soup 库
简称 : bs4,进行html或者xml的解析,更好的提取元素
from bs4 import BeautifulSoup
soup = BeautifulSoup(r.text, 'html.parser')
# lxml、xml
# 标签数据
soup.title
soup.a
# 标签的属性
tag = soup.a
tag.attrs# 一个字典
tag.attrs["href"]
# 标签的内容,包括了子的内容
tag.string