python抓取网页数据(学习利用Python中的selenium模块启动Chromium学习过程开发工具)

优采云 发布时间: 2021-12-28 15:12

  python抓取网页数据(学习利用Python中的selenium模块启动Chromium学习过程开发工具)

  一、前言

  笔者在上一篇文章中采集

了一些域名。采集

这些域名后,并不是每个域名都有用。我们要过滤掉无法访问的网站。所以今天我们学习使用Python中的selenium模块来启动Chromium来请求网站。, 下面记录下自己的学习过程。

  二、学习过程

  1.开发工具:

  Python版本:3.7.1

  相关模块:

  selenium模块

pymysql模块

  2. 原理介绍

  从数据库中读取需要访问的域名------使用selenium访问域名并获取网站标题、内容长度、截图------保存到数据库中

  from selenium import webdriver

from selenium.webdriver.chrome.options import Options

import pymysql

# 获取存活的域名

def run(cursor):

# 获取域名

domains = get_domains(cursor)

# Chrome的参数选项

chrome_options = Options()

# 无头操作

chrome_options.add_argument(‘--headless‘)

# 利用这个路径的Chromium来进行操作

chrome_options.binary_location = r‘%s‘%"/Applications/Chromium.app/Contents/MacOS/Chromium"

# 创建Chrome实例

driver = webdriver.Chrome(executable_path=(r‘/Users/hello/Desktop/chromedriver/chromedriver‘), options=chrome_options)

# 设置20秒的超时时间

driver.set_page_load_timeout(20)

success_list = []

for i in domains:

try:

# 请求网站

driver.get(‘https://‘+i[0])

#获取网站的信息

http_length = len(driver.page_source)

http_status = ‘响应成功‘

img_path = "/Users/hello/Desktop/py test/%s.png"%i[0]

screenshot = driver.get_screenshot_as_file(img_path)

if driver.title:

title = driver.title

else:

title = ‘‘

success_list.append([i[0], title, http_length, img_path, http_status])

except :

print(‘%s 响应失败‘%i[0])

return success_list

# 去数据库查询域名

def get_domains(cursor):

sql = "SELECT hostname FROM 数据库"

cursor.execute(sql)

domain_lists = cursor.fetchall()

return domain_lists

# 把可访问的域名插入数据库

def insert(cursor, list, db):

for i in list:

select_sql = "SELECT id FROM 数据库 WHERE hostname = ‘%s‘"%i[0]

cursor.execute(select_sql)

result = cursor.fetchone()

update_sql = "UPDATE 数据库 SET page_title = ‘%s‘, http_length = %d, page_jietu_path = ‘%s‘, http_status= ‘%s‘ WHERE id = %s" %(i[1], i[2], i[3], i[4], result[0])

cursor.execute(update_sql)

db.commit()

if __name__ == "__main__":

db = pymysql.connect(‘localhost‘, ‘账户‘, ‘密码‘, ‘test‘)

cursor = db.cursor()

list = run(cursor)

insert(cursor, list, db)

db.close()

  三、效果展示

  

  四、总结

  程序速度慢,编写程序的能力有待加强。

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线