本实验采用python3.6环境
1. 实验目的
掌握爬虫工作的基本原理,并完成一定的任务。
1.1 编写爬虫脚本使其可以工作 1.2 完成批量爬取文本文章的任务(单一网站) 1.3 将文本文章转存到mysql数据库和项目文件夹中
2. 相关知识
2.1 python基础知识学习
python3 字符串基本操作 |
python3 file操作 |
python3 os操作
2.2 python爬虫知识学习
2.3 pymysql的使用
python mysql-connector驱动 |
pymysql操作
2.4 其他相关
3. 爬虫实现
3.1爬虫初步实现
(1)我们爬取中国化工市场机械网,以下为相关代码演示
import requests from bs4 import BeautifulSoup
res = requests.get(addresses[i])
res.encoding = 'GB18030' # 通过修改编码方式为GB18030,兼容网站编码(gb2312) # 这里的'html.parser'是为了告诉BeautifulSoup这个html_sample的解析形式是html格式# soup = BeautifulSoup(res.text, 'html.parser') article_content = soup.select( '#NewsMainLeft > div.mainBox.MarginTop10.articleBox > div.article > div.ArticleMatter') article_title = soup.select( '#NewsMainLeft > div.mainBox.MarginTop10.articleBox > div.article > div.articleTitle > h1')
此处select()中的内容,可以使用chrome浏览器的开发者模式,选中该标签,右键copy->copy selector,再复制到select()中,更精确。
利用print()方法可以将爬下来的字段打印出来。
但是只可以爬取单一网址下的内容,如果想批量爬取改网站文章,就需要多次更改爬取的网址,不合理。
(2)我发现有两个办法可以实现批量的爬取
- 发现网址之间的规律,使用循环每次更改网址,但是使用中发现网址的变化有时会脱离规律,在运行过程中会出现一些错误,因此不推荐使用该方法。
- 另一种方法是:再爬取网站内的下一篇的<a>标签内的href属性,作为返回值,使用到下一次循环当中。如下代码演示:
next_address = soup.select(
'#NewsMainLeft > div.mainBox.MarginTop10.articleBox > div.article > div.arNext > a[href]')
3.2 爬取文本初步整理
爬取下来的文本,我发现有一些位置出现不必要的字符、回车等,这些如果无法处理,将影响到后期存储数据,故需要清除,代码如下:
for s in article_title: delete = str(s.contents) title = delete.replace('[\'', '').replace('\']', '').replace('\\r', '').replace('\\n', '').replace('\\t', '')\ .replace('\\', '').replace('/', '').replace(':', '').replace('*', '').replace('?', '').replace('\"', '')\ .replace('<', '').replace('>', '').replace('|', '') for t in article_content: delete = str(t.contents) context = delete.replace('[\'', '').replace('\']', '').replace('\\r', '').replace('\\n', '').replace('\\t', '')\ .replace('\\u3000', '').replace('\', <br/>,', '').replace('<br/>, \'', '').replace('<br/>,', '')\ .replace('<br/>', '').replace('</p>', '').replace('<p>', '').replace(' ', '').replace('\'', '').lstrip('\'') title_and_context = title+'。'+context if title_and_context[len(title_and_context)-1] == "\'": title_and_context = title_and_context[:len(title_and_context)-1] + ''
经过上述处理,文本信息初步处理完毕

3.3 文章存储
(1)涉及编码问题,首先,被爬取的网页的编码为gb2312,但是在爬取过程中,如:“槃”字仍无法识别报错,我将爬虫的爬取编码设为gb18030,问题解决。gb18030是gb2312和gbk编码扩大后的编码格式,支持的汉字更多。
(2)数据库也需要设置,通常,mysql默认建立数据库和表的编码是utf-8,在这里,我改成gb18030防止存入数据库时出错.

(3)保存为.txt
# 保存到文本文件当中 def save_files(path, curr_file_name, curr_content): if os.path.exists(path): # 判断文件夹是否存在 os.chdir(path) # 进入文件夹 elif os.getcwd()[-len(path):] == path: print("本篇文章已存入") else: os.mkdir(path) # 创建文件夹 os.chdir(path) # 进入文件夹 f = open(curr_file_name, 'w', encoding='GB18030') f.write(curr_content) f.close() print(os.getcwd())
(4)保存到数据库
- 建立数据库连接
util.py
import mysql.connector def get_connect(curr_host, curr_user, curr_passwd, curr_database): my_db = mysql.connector.connect( host=curr_host, # 数据库主机地址 user=curr_user, # 数据库用户名 passwd=curr_passwd, # 数据库密码 database=curr_database # 进入数据库 ) my_cursor = my_db.cursor() return my_cursor, my_db
- 创建数据库
import mysql.connector
# my_cursor.execute("CREATE DATABASE articles_db") # my_cursor.execute("USE articles_db") my_db = mysql.connector.connect( host="localhost", # 数据库主机地址 user="root", # 数据库用户名 passwd="123", # 数据库密码 database="articles_db" # 进入数据库 ) my_cursor = my_db.cursor() my_cursor.execute( "CREATE TABLE articles_tb (id INT AUTO_INCREMENT PRIMARY KEY, htmlId varchar(255), context MEDIUMTEXT)")
- 保存到数据库中
# 保存到mysql中 def save_files_to_mysql(curr_file_name, curr_content): my_cursor, my_db = util.get_connect("localhost", "root", "123", "articles_db") sql_1 = "INSERT INTO articles_tb (htmlId,context)VALUES(\'" sql_2 = "\',\'" sql_3 = "\')" sql = sql_1+curr_file_name+sql_2+curr_content+sql_3 print("sql:" + sql) my_cursor.execute(sql) my_db.commit() # 提交到数据库执行,必须一步勿忘 my_cursor.close() my_db.close
4.总结
4.1
我通过爬虫,爬取到了一定量的数据,后面的计划是利用这些文本,经过一系列的操作,如数据清洗、三元组提取、知识图谱的建立等,实现一个一定领域内的搜索功能。
4.2
关于爬虫,有很多值得使用的框架,如pyspider、Scrapy等,后期学习之后会进行进一步的改进。