本實驗採用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等,後期學習以後會進行進一步的改進。