Python网络爬虫与信息提取

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值