爬虫实战----简书的爬取和存储

网站:

https://www.jianshu.com/

网站数据结构分析:

滑轮拉到最下面:

这是一个懒加载,只有点击阅读更多的时候,才会有后续的数据,我们可以使用selenium。

并且可以设置点击的次数,代码如下:

browser = webdriver.Chrome()
browser.get('https://www.jianshu.com/')

for i in range(3):
    # 将滑轮滑到底部
    browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(2)

for i in range(5):
    # 尝试点击阅读更多的按钮
    try:
        button = browser.find_element_by_class_name('load-more')
        button.click()
        time.sleep(2)
    except Exception as e:
        pass

提取数据:

需要的数据都在a标签中,提取数据代码如下:

titles = browser.find_elements_by_class_name('title')

存储数据:

def db(titles):
    print(titles)
    db = pymysql.connect(host = 'localhost',user = 'root',password='123456',port=3306,db='images360',charset='utf8')
    cursor = db.cursor()
    for info in titles:
        # print(info)
        sql = "insert into  jianshu values('%s','%s')" % (info.text,info.get_attribute('href'))
        try:
            cursor.execute(sql)
            print('Successful')
            db.commit()
        except Exception as e:
            print('Failed',e)
    cursor.close()
    db.close()

数据库和表都是自己创建的。运行之后就可以获得自己想要的结果了。

创建数据库代码如下:

CREATE DATABASE images360

创建表的代码如下:

CREATE TABLE jianshu
(
title VARCHAR(255),
href VARCHAR(255)
)

猜你喜欢

转载自blog.csdn.net/qq_39138295/article/details/83899387