selenium 介绍
selenium 是一个 web 自动化测试工具,也可以用来爬取网页信息。 参考 selenium 简介
视频资料参考 Python 爬虫视频资料中的 selenium
环境
- 需要安装 Chrome 或者 Firefox 浏览器,这里使用 Chrome 浏览器。chrome 下载地址
- 使用
pip3 install selenium --user
安装 selenium 包。 - 下载对应浏览器的驱动。selenium 对应的 chrome 驱动下载
任务介绍
爬取证券交易所网站中所有的证券代码,证券简称,监管类型,处理事由,涉及对象,处理日期等信息。
一共 169 分页。使用 selenium 模拟人工方式得到对应的信息。具体方法为自动在 GO 按钮前的输入框中输入数字,自动化点击,之后得到分页的信息。
实例代码
#-*- coding:utf-8 -*- from selenium import webdriver import selenium import time import random browser = webdriver.Chrome('/home/z/Downloads/chromedriver') browser.get('http://www.sse.com.cn/disclosure/credibility/supervision/measures/') i = 1 outlines = [] while i <= 169: flag = True while flag: try: ht_input = browser.find_element_by_id('ht_codeinput') btn_more = browser.find_element_by_id('pagebutton') flag = False except selenium.common.exceptions.NoSuchElementException: time.sleep(random.randint(1,3)) ht_input.clear() ht_input.send_keys(str(i)) btn_more.click() flag = True while flag: try: table = browser.find_element_by_id('panel-1') lines = table.find_elements_by_tag_name('tr') for j in range(1,len(lines)): print(lines[j].text) outlines.append(lines[j].text) flag = False except selenium.common.exceptions.NoSuchElementException: time.sleep(random.randint(1,3)) except selenium.common.exceptions.StaleElementReferenceException: time.sleep(random.randint(1,3)) i += 1 print(i) #browser.quit() with open('out.txt','w') as f: for line in outlines: f.write(line + '\n')
注意对应 id 可以通过鼠标右键审查元素在 html 文本中找到。如果需要执行 js 代码,可以通过构建 js 代码的字符串,然后使用 browser.execute_script(js)
来运行。
运行结果
使用 python3 程序文件名.py
运行
生成的 out.txt 文件截图如下
共爬取 3443 条信息。注意,有个别几条数据有重复,这是因为相邻页面的内容有重复。并且存在个别的数据是在多行,这是因为处理事由信息里会有换行。
原创文章,转载请注明出处:https://www.daiyufish.com/article/selenium_example/