本实验采用python3.6环境javascript
掌握爬虫工做的基本原理,并完成必定的任务。css
1.1 编写爬虫脚本使其能够工做 1.2 完成批量爬取文本文章的任务(单一网站) 1.3 将文本文章转存到mysql数据库和项目文件夹中
python3 字符串基本操做 |
python3 file操做 |
python3 os操做html
BeautifulSoup |
python 爬虫介绍java
python mysql-connector驱动 |
pymysql操做python
遇到的问题 |
bs4.select()mysql
(1)咱们爬取中国化工市场机械网,如下为相关代码演示sql
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()中,更精确。chrome
利用print()方法能够将爬下来的字段打印出来。数据库
可是只能够爬取单一网址下的内容,若是想批量爬取改网站文章,就须要屡次更改爬取的网址,不合理。浏览器
(2)我发现有两个办法能够实现批量的爬取
next_address = soup.select(
'#NewsMainLeft > div.mainBox.MarginTop10.articleBox > div.article > div.arNext > a[href]')
爬取下来的文本,我发现有一些位置出现没必要要的字符、回车等,这些若是没法处理,将影响到后期存储数据,故须要清除,代码以下:
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] + ''
通过上述处理,文本信息初步处理完毕
(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
我经过爬虫,爬取到了必定量的数据,后面的计划是利用这些文本,通过一系列的操做,如数据清洗、三元组提取、知识图谱的创建等,实现一个必定领域内的搜索功能。
关于爬虫,有不少值得使用的框架,如pyspider、Scrapy等,后期学习以后会进行进一步的改进。