Requests-HTML库(Python爬虫) 开源软件 前端资源


https://github.com/kennethreitz/requests-html/

http://html.python-requests.org/


案例一:

文档地址:http://html.python-requests.org/

试着爬取了《伯乐在线》:http://python.jobbole.com/all-posts/ (得罪得罪!)就爬一页,试试好用不!


代码如下:

from requests_html import HTMLSession
from datetime import datetime
def HtmlDownloader(url):
    try:
        if url is None:
            return
        session = HTMLSession()
        r = session.get(url)
        return r.html
    except:
        return
def HtmlParser(url,html,path):
    date = {}
    postList = html.find('div.post')
    for post in postList:
        date['name'] = post.find('a.archive-title',first=True).text
        date['img_url'] = post.find('div.post-thumb',first=True).find('img',first=True).attrs['src']
        detail_url = post.find('span.read-more',first=True).find('a',first=True).attrs['href']
        date['detail_url'] = detail_url
        date['detail'] = HtmlDetailedParser(detail_url)[:12]
        date['time'] = datetime.now()
        with open(path,'a',encoding='utf-8') as f:
            f.write(str(date))
            f.write('\n')
def HtmlDetailedParser(url):
    html = HtmlDownloader(url)
    content = html.find('div.entry',first=True).text
    return content
def HtmlMian():
    path = 'F:\python_work\\text.txt'
    url = 'http://python.jobbole.com/all-posts/page/1/'
    html = HtmlDownloader(url)
    HtmlParser(url, html, path)
HtmlMian()


案例二:

代码撸多了,让我们看会妹纸,爬的网站我选的是 http://www.win4000.com/zt/xinggan.html

打开网站,观察到这是个列表,图片是缩略图,要想保存图片到本地.

当然需要高清大图,因此得进入列表详情,进一步解析.

完整代码如下:

from requests_html import HTMLSession
import requests
import time
session = HTMLSession()
# 解析图片列表
def get_girl_list():
    # 返回一个 response 对象
    response = session.get('http://www.win4000.com/zt/xinggan.html')  # 单位秒数
    content = response.html.find('div.Left_bar', first=True)
    li_list = content.find('li')
    for li in li_list:
        url = li.find('a', first=True).attrs['href']
        get_girl_detail(url)
# 解析图片详细
def get_girl_detail(url):
    # 返回一个 response 对象
    response = session.get(url)  # 单位秒数
    content = response.html.find('div.scroll-img-cont', first=True)
    li_list = content.find('li')
    for li in li_list:
        img_url = li.find('img', first=True).attrs['data-original']
        img_url = img_url[0:img_url.find('_')] + '.jpg'
        print(img_url + '.jpg')
        save_image(img_url)
# 保持大图
def save_image(img_url):
    img_response = requests.get(img_url)
    t = int(round(time.time() * 1000))  # 毫秒级时间戳
    f = open('/Users/wuxiaolong/Desktop/Girl/%d.jpg' % t, 'ab')  # 存储图片,多媒体文件需要参数b(二进制文件)
    f.write(img_response.content)  # 多媒体存储content
    f.close()
if __name__ == '__main__':
    get_girl_list()

代码就这么多,是不是感觉很简单啊。

说明:

1、requests-html 与 BeautifulSoup 不同,可以直接通过标签来 find,一般如下:
标签
标签.someClass
标签#someID
标签[target=_blank]
参数 first 是 True,表示只返回 Element 找到的第一个,更多使用:http://html.python-requests.org/ ;

2、这里保存本地路径 /Users/wuxiaolong/Desktop/Girl/我写死了,需要读者改成自己的,如果直接是文件名,保存路径将是项目目录下。

遗留问题

示例所爬网站是分页的,没有做,可以定时循环来爬妹纸哦,有兴趣的读者自己玩下。


案例三. 初探python之做一个简单小爬虫

分析需求: 做一个小爬虫离不开获取网页内容和匹配存储内容,

那么我们先装上python爬虫的老朋友,requests:pip install requests 

再装上pymysql扩展.方便将匹配到的内容插入到mysql数据库中:pip install pymysql.

第一步:获取网页内容

# -*- coding:utf-8 -*-
# 加载 requests 模块
import requests
# GET方式获取 Response 对象
response = requests.get('https://www.xxx.com/')
if response:
    # 输出html代码到控制台
    print(response.text)
else:
    # 输出错误信息
    print('requests error')

第二步:正则匹配内容

既然能够获取html代码,那我们就要找出需要的部分,这就用上了正则。Python 自1.5版本起增加了 re 模块,它提供 Perl 风格的正则表达式模式。具体细节可以在菜鸟教程中查看:http://www.runoob.com/python/python-reg-expressions.html,话不多说再贴代码:

# -*- coding:utf-8 -*-
# 加载 requests 模块
import requests
# 加载 re 模块
import re
response = requests.get('https://www.xxx.com/')
# 正则匹配文本
match = re.findall(r'<p><!--markdown-->([\s\S]*?)</p>', response.text)
if match:
    # 输出匹配的内容到控制台
    print(match[0])
else:
    # 输出html代码到控制台
    print(response.text)

第三步:循环匹配并加入数据库中

首先我们把数据库和表做好,可以用sql语句创建:
CREATE DATABASE IF NOT EXISTS `sentence`;
USE `sentence`;
CREATE TABLE IF NOT EXISTS `sexy` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `content` varchar(50) NOT NULL,
  `datetime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `content` (`content`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

这里将content设置为了UNIQUE KEY,是为了保证抓取到的内容不重复,如果有已存在的值便直接跳过

# -*- coding:utf-8 -*-
# 加载 requests 模块
import requests
# 加载 re 模块
import re
# 加载 pymysql 模块
import pymysql
# 打开数据库连接
db = pymysql.connect('127.0.0.1', 'root', 'root', 'sentence', charset='utf8')
# 使用cursor()方法获取操作游标
cursor = db.cursor()
#死循环到天长地久
while(True):
    response = requests.get('https://www.xxx.com/')
    # 正则匹配文本
    match = re.findall(r'<p><!--markdown-->([\s\S]*?)</p>', response.text)
    if match:
        sql = '''INSERT INTO sexy (content) VALUES (%s) % (match[0])'''  #向sql语句传递参
        try:
           # 执行sql语句
           cursor.execute(sql)
           # 提交到数据库执行
           db.commit()
        except:
           # 如果发生错误则回滚
           db.rollback()
        # 输出sql语句到控制台
        print(sql)
    else:
        # 输出html代码到控制台
        print(response.text)
# 关闭游标
cursor.close()
# 关闭连接
conn.close()

运行演示,查看数据库内容.

源码在Github中:https://github.com/st1ven/Python-Spider-Demo

spider.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests
import re
import pymysql
# 打开数据库连接
db = pymysql.connect('127.0.0.1', 'root', 'root', 'sentence', charset='utf8')
# 使用cursor()方法获取操作游标
cursor = db.cursor()
#死循环到天长地久
while(True):
    response = requests.get('https://www.nihaowua.com/')
    # 正则匹配文本
    match = re.findall(r'<p><!--markdown-->([\s\S]*?)</p>', response.text)
    if match:
        sql = "INSERT INTO `sexy` (`content`) VALUES ('%s')" % (match[0])  #向sql语句传递参数
        try:
           # 执行sql语句
           cursor.execute(sql)
           # 提交到数据库执行
           db.commit()
        except:
           # 如果发生错误则回滚
           db.rollback()
        # 输出sql语句到控制台
        print(sql)
    else:
        # 输出html代码到控制台
        print(response.text)
#db.close()

spider.sql

-- 导出 sentence 的数据库结构
CREATE DATABASE IF NOT EXISTS `sentence` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `sentence`;
-- 导出  表 sentence.sexy 结构
CREATE TABLE IF NOT EXISTS `sexy` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `content` varchar(250) NOT NULL,
  `datetime` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `content` (`content`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

四.注意符号

cursor.execute('''insert into `%s`(id) values("%s")''' % (tb_name,data))  # 使用了三引号和双引号做区分
sql_insert = '''insert into user(id, name) values (2, "李明")'''   # '''事务机制可以确保数据的一致

五.

5.1查询操作
import pymysql  #导入 pymysql 
#打开数据库连接  
db= pymysql.connect(host="localhost",user="root",  
    password="123456",db="test",port=3307)   
# 使用cursor()方法获取操作游标  
cur = db.cursor()  
#1.查询操作  
# 编写sql 查询语句  user 对应我的表名  
sql = "select * from user"  
try:  
    cur.execute(sql)    #执行sql语句  
  
    results = cur.fetchall()    #获取查询的所有记录  
    print("id","name","password")  
    #遍历结果  
    for row in results :  
        id = row[0]  
        name = row[1]  
        password = row[2]  
        print(id,name,password)  
except Exception as e:  
    raise e  
finally:  
    db.close()  #关闭连接 
     
5.2插入操作
import pymysql  
#2.插入操作  
db= pymysql.connect(host="localhost",user="root",  
    password="123456",db="test",port=3307) 
# 使用cursor()方法获取操作游标  
cur = db.cursor()  
sql_insert ="""insert into user(id,username,password) values(4,'liu','1234')"""   
try:  
    cur.execute(sql_insert)  
    #提交  
    db.commit()  
except Exception as e:  
    #错误回滚  
    db.rollback()   
finally:  
    db.close() 
     
5.3更新操作
import pymysql  
#3.更新操作  
db= pymysql.connect(host="localhost",user="root",  
    password="123456",db="test",port=3307) 
# 使用cursor()方法获取操作游标  
cur = db.cursor()   
sql_update ="update user set username = '%s' where id = %d" 
try:  
    cur.execute(sql_update % ("xiongda",3))  #像sql语句传递参数  
    #提交  
    db.commit()  
except Exception as e:  
    #错误回滚  
    db.rollback()   
finally:  
    db.close()  
    
5.4删除操作
import pymysql  
#4.删除操作  
db= pymysql.connect(host="localhost",user="root",  
    password="123456",db="test",port=3307)   
# 使用cursor()方法获取操作游标  
cur = db.cursor() 
sql_delete ="delete from user where id = %d"  
try:  
    cur.execute(sql_delete % (3))  #像sql语句传递参数  
    #提交  
    db.commit()  
except Exception as e:  
    #错误回滚  
    db.rollback()   
finally:  
    db.close()

六.Python中操作mysql的pymysql模块详解

1、执行SQL
#!/usr/bin/env pytho
# -*- coding:utf-8 -*-
import pymysql
# 创建连接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='tkq1', charset='utf8')
# 创建游标
cursor = conn.cursor( 
# 执行SQL,并返回收影响行数
effect_row = cursor.execute("select * from tb7") 
# 执行SQL,并返回受影响行数
#effect_row = cursor.execute("update tb7 set pass = '123' where nid = %s", (11,))
# 执行SQL,并返回受影响行数,执行多次
#effect_row = cursor.executemany("insert into tb7(user,pass,licnese)values(%s,%s,%s)", [("u1","u1pass","11111"),("u2","u2pass","22222")])
# 提交,不然无法保存新建或者修改的数据
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()
注意:存在中文的时候,连接需要添加charset='utf8',否则中文显示乱码。

2、获取查询数据
#! /usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = "TKQ"
import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='tkq1')
cursor = conn.cursor()
cursor.execute("select * from tb7")
# 获取剩余结果的第一行数据
row_1 = cursor.fetchone()
print row_1
# 获取剩余结果前n行数据
# row_2 = cursor.fetchmany(3)
# 获取剩余结果所有数据
# row_3 = cursor.fetchall()
conn.commit()
cursor.close()
conn.close()

3、获取新创建数据自增ID
可以获取到最新自增的ID,也就是最后插入的一条数据ID
#! /usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = "TKQ"
import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='tkq1')
cursor = conn.cursor()
effect_row = cursor.executemany("insert into tb7(user,pass,licnese)values(%s,%s,%s)", [("u3","u3pass","11113"),("u4","u4pass","22224")])
conn.commit()
cursor.close()
conn.close()
#获取自增id
new_id = cursor.lastrowid      
print new_id

4、移动游标
操作都是靠游标,那对游标的控制也是必须的
注:在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:
cursor.scroll(1,mode='relative') # 相对当前位置移动
cursor.scroll(2,mode='absolute') # 相对绝对位置移动
 
5、fetch数据类型
关于默认获取的数据是元祖类型,如果想要或者字典类型的数据,即:
#! /usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = "TKQ"
import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='tkq1')
#游标设置为字典类型
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("select * from tb7")
row_1 = cursor.fetchone()
print row_1  #{u'licnese': 213, u'user': '123', u'nid': 10, u'pass': '213'}
conn.commit()
cursor.close()
conn.close()

6、调用存储过程
a、调用无参存储过程
#! /usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = "TKQ"
import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='tkq1')
#游标设置为字典类型
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
#无参数存储过程
cursor.callproc('p2')  #等价于cursor.execute("call p2()")
row_1 = cursor.fetchone()
print row_1
conn.commit()
cursor.close()
conn.close()
b、调用有参存储过程
#! /usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = "TKQ"
import pymysql
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='tkq1')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.callproc('p1', args=(1, 22, 3, 4))
#获取执行完存储的参数,参数@开头
cursor.execute("select @p1,@_p1_1,@_p1_2,@_p1_3")  #{u'@_p1_1': 22, u'@p1': None, u'@_p1_2': 103, u'@_p1_3': 24}
row_1 = cursor.fetchone()
print row_1
conn.commit()
cursor.close()
conn.close()


签名:这个人很懒,什么也没有留下!
最新回复 (0)
返回