Python常用爬虫代码总结方便查询


Posted in Python onFebruary 25, 2019

beautifulsoup解析页面

from bs4 import BeautifulSoup
soup = BeautifulSoup(htmltxt, "lxml")
# 三种装载器
soup = BeautifulSoup("<a></p>", "html.parser")
### 只有起始标签的会自动补全,只有结束标签的会自动忽略
### 结果为:<a></a>
soup = BeautifulSoup("<a></p>", "lxml")
### 结果为:<html><body><a></a></body></html>
soup = BeautifulSoup("<a></p>", "html5lib")
### html5lib则出现一般的标签都会自动补全
### 结果为:<html><head></head><body><a><p></p></a></body></html>
# 根据标签名、id、class、属性等查找标签
### 根据class、id、以及属性alog-action的值和标签类别查询
soup.find("a",class_="title",id="t1",attrs={"alog-action": "qb-ask-uname"}))
### 查询标签内某属性的值
pubtime = soup.find("meta",attrs={"itemprop":"datePublished"}).attrs['content']
### 获取所有class为title的标签
for i in soup.find_all(class_="title"):
  print(i.get_text())
### 获取特定数量的class为title的标签
for i in soup.find_all(class_="title",limit = 2):
  print(i.get_text())
### 获取文本内容时可以指定不同标签之间的分隔符,也可以选择是否去掉前后的空白。
soup = BeautifulSoup('<p class="title" id="p1"><b> The Dormouses story </b></p><p class="title" id="p1"><b>The Dormouses story</b></p>', "html5lib")
soup.find(class_="title").get_text("|", strip=True)
#结果为:The Dormouses story|The Dormouses story
### 获取class为title的p标签的id
soup.find(class_="title").get("id")
### 对class名称正则:
soup.find_all(class_=re.compile("tit"))
### recursive参数,recursive=False时,只find当前标签的第一级子标签的数据
soup = BeautifulSoup('<html><head><title>abc','lxml')
soup.html.find_all("title", recursive=False)

unicode编码转中文

content = "\u65f6\u75c7\u5b85"
content = content.encode("utf8","ignore").decode('unicode_escape')

url encode的解码与解码

from urllib import parse
# 编码
x = "中国你好"
y = parse.quote(x)
print(y)
# 解码
x = parse.unquote(y)
print(x)

html转义字符的解码

from html.parser import HTMLParser
htmls = "<div><p>"
txt = HTMLParser().unescape(htmls)
print(txt)  . # 输出<div><p>

base64的编码与解码

import base64
# 编码
content = "测试转码文本123"
contents_base64 = base64.b64encode(content.encode('utf-8','ignore')).decode("utf-8")
# 解码
contents = base64.b64decode(contents_base64)

过滤emoji表情

def filter_emoji(desstr,restr=''):
    try:
      co = re.compile(u'[\U00010000-\U0010ffff]')
    except re.error:
      co = re.compile(u'[\uD800-\uDBFF][\uDC00-\uDFFF]')
    return co.sub(restr, desstr)

完全过滤script和style标签

import requests
from bs4 import BeautifulSoup
soup = BeautifulSoup(htmls, "lxml")
for script in soup(["script", "style"]):  
  script.extract()
print(soup)

过滤html的标签,但保留标签里的内容

import re
htmls = "<p>abc</p>"
dr = re.compile(r'<[^>]+>',re.S)
htmls2 = dr.sub('',htmls)
print(htmls2)  #abc
正则提取内容(一般处理json)
rollback({
 "response": {
 "code": "0",
 "msg": "Success",
 "dext": ""
 },
 "data": {
 "count": 3,
 "page": 1,
 "article_info": [{
  "title": "“小库里”:适应比赛是首要任务 投篮终会找到节奏",
  "url": "http:\/\/sports.qq.com\/a\/20180704\/035378.htm",
  "time": "2018-07-04 16:58:36",
  "column": "NBA",
  "img": "",
  "desc": ""
 }, {
  "title": "首钢体育助力国家冰球集训队 中国冰球联赛年底启动",
  "url": "http:\/\/sports.qq.com\/a\/20180704\/034698.htm",
  "time": "2018-07-04 16:34:44",
  "column": "综合体育",
  "img": "",
  "desc": ""
 }...]
 }
})
import re
# 提取这个json中的每条新闻的title、url
# (.*?)为要提取的内容,可以在正则字符串中加入.*?表示中间省略若干字符
reg_str = r'"title":"(.*?)",.*?"url":"(.*?)"'
pattern = re.compile(reg_str,re.DOTALL)
items = re.findall(pattern,htmls)
for i in items:
  tilte = i[0]
  url = i[1]

时间操作

# 获取当前日期
today = datetime.date.today()
print(today)   #2018-07-05
# 获取当前时间并格式化
time_now = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))
print(time_now)   #2018-07-05 14:20:55
# 对时间戳格式化
a = 1502691655
time_a = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(a))) 
print(time_a)    #2017-08-14 14:20:55
# 字符串转为datetime类型
str = "2018-07-01 00:00:00"
datetime.datetime.strptime(st, "%Y-%m-%d %H:%M:%S")
# 将时间转化为时间戳
time_line = "2018-07-16 10:38:50"
time_tuple = time.strptime(time_line, "%Y-%m-%d %H:%M:%S")
time_line2 = int(time.mktime(time_tuple))
# 明天的日期
today = datetime.date.today()
tomorrow = today + datetime.timedelta(days=1)
print(tomorrow)   #2018-07-06
# 三天前的时间
today = datetime.datetime.today()
tomorrow = today + datetime.timedelta(days=-3)
print(tomorrow)   #2018-07-02 13:37:00.107703
# 计算时间差
start = "2018-07-03 00:00:00"
time_now = datetime.datetime.now()
b = datetime.datetime.strptime(start,'%Y-%m-%d %H:%M:%S')
minutes = (time_now-b).seconds/60
days = (time_now-b).days
all_minutes = days*24*60+minutes
print(minutes)   #821.7666666666667
print(days)   #2
print(all_minutes)   #3701.7666666666664

数据库操作

import pymysql
conn = pymysql.connect(host='10.0.8.81', port=3306, user='root', passwd='root',db='xxx', charset='utf8')
cur = conn.cursor()
insert_sql = "insert into tbl_name(id,name,age) values(%s,%s,%s)
id = 1
name = "like"
age = 26
data_list = []
data = (id,name,age)
# 单条插入
cur.execute(insert_sql,data)
conn.commit()
# 批量插入
data_list.append(data)
cur.executemany(insert_sql,data_list)
conn.commit()
#特殊字符处理(name中含有特殊字符)
data = (id,pymysql.escape_string(name),age)
#更新
update_sql = "update tbl_name set content = '%s' where id = "+str(id)
cur.execute(update_sql%(pymysql.escape_string(content)))
conn.commit()
#批量更新
update_sql = "UPDATE tbl_recieve SET content = %s ,title = %s , is_spider = %s WHERE id = %s"
update_data = (contents,title,is_spider,one_new[0])
update_data_list.append(update_data)
if len(update_data_list) > 500:
try:
  cur.executemany(update_sql,update_data_list) 
  conn.commit()

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对三水点靠木的支持。如果你想了解更多相关内容请查看下面相关链接

Python 相关文章推荐
python之模拟鼠标键盘动作具体实现
Dec 30 Python
Python中集合的内建函数和内建方法学习教程
Aug 19 Python
python 中文件输入输出及os模块对文件系统的操作方法
Aug 27 Python
Python实现批量执行同目录下的py文件方法
Jan 11 Python
使用Django简单编写一个XSS平台的方法步骤
Mar 25 Python
Python实战之制作天气查询软件
May 14 Python
python读取.mat文件的数据及实例代码
Jul 12 Python
Django文件存储 默认存储系统解析
Aug 02 Python
如何把外网python虚拟环境迁移到内网
May 18 Python
如何解决cmd运行python提示不是内部命令
Jul 01 Python
通过代码实例了解Python sys模块
Sep 14 Python
numpy array找出符合条件的数并赋值的示例代码
Jun 01 Python
Python使用paramiko操作linux的方法讲解
Feb 25 #Python
详解Django中CBV(Class Base Views)模型源码分析
Feb 25 #Python
Python判断对象是否相等及eq函数的讲解
Feb 25 #Python
详解django中url路由配置及渲染方式
Feb 25 #Python
利用python脚本如何简化jar操作命令
Feb 24 #Python
Python中如何使用if语句处理列表实例代码
Feb 24 #Python
python实现两张图片的像素融合
Feb 23 #Python
You might like
php读取数据库信息的几种方法
2008/05/24 PHP
php mysql like 实现多关键词搜索的方法
2016/10/29 PHP
Laravel Eloquent分表方法并使用模型关联的实现
2019/11/25 PHP
jQuery中绑定事件的命名空间详解
2011/04/05 Javascript
javascript抖动元素的小例子
2013/10/28 Javascript
jquery 缓存问题的几个解决方法
2013/11/11 Javascript
javascript实现单击和双击并存的方法
2014/12/13 Javascript
node.js中的fs.lstat方法使用说明
2014/12/16 Javascript
Jquery实现仿腾讯娱乐频道焦点图(幻灯片)特效
2015/03/06 Javascript
分步解析JavaScript实现tab选项卡自动切换功能
2016/01/25 Javascript
jQuery+css实现的tab切换标签(兼容各浏览器)
2016/01/28 Javascript
微信小程序点餐系统开发常见问题汇总
2019/08/06 Javascript
基于JS判断对象是否是数组
2020/01/10 Javascript
js实现整体缩放页面适配移动端
2020/03/31 Javascript
vue通过v-html指令渲染的富文本无法修改样式的解决方案
2020/05/20 Javascript
Bootstrap FileInput实现图片上传功能
2021/01/28 Javascript
Python md5与sha1加密算法用法分析
2017/07/14 Python
使用Pyinstaller的最新踩坑实战记录
2017/11/08 Python
python 矩阵增加一行或一列的实例
2018/04/04 Python
对Python中TKinter模块中的Label组件实例详解
2019/06/14 Python
Django项目使用ckeditor详解(不使用admin)
2019/12/17 Python
Python嵌套函数,作用域与偏函数用法实例分析
2019/12/26 Python
Python开发之pip安装及使用方法详解
2020/02/21 Python
PyTorch中model.zero_grad()和optimizer.zero_grad()用法
2020/06/24 Python
结合 CSS3 transition transform 实现简单的跑马灯效果的示例
2018/02/07 HTML / CSS
几个常见的消息中间件(MOM)
2014/01/08 面试题
应届生服装设计自我评价
2013/09/20 职场文书
消防先进事迹材料
2014/02/10 职场文书
“学雷锋活动月”总结
2014/03/09 职场文书
总结表彰大会主持词
2014/03/26 职场文书
《分一分》教学反思
2014/04/13 职场文书
班风口号
2014/06/18 职场文书
行政专员岗位职责范本
2014/08/26 职场文书
群众路线个人剖析材料及整改措施
2014/11/04 职场文书
酒店人事专员岗位职责
2015/04/07 职场文书
PL350与SW11的比较
2021/04/22 无线电