网易Python爬虫:爬取网易科技频道文章存入MySQL数据库
第一篇博客里答應(yīng)的,第二篇會(huì)用 pymysql 直接將數(shù)據(jù)存入 MySQL 數(shù)據(jù)庫(kù)。
代碼部分只注釋了數(shù)據(jù)庫(kù)操作的部分,爬蟲部分有時(shí)間會(huì)補(bǔ)上。
網(wǎng)易科技頻道 以獨(dú)特視角呈現(xiàn)科技圈內(nèi)大事小事,內(nèi)容包括互聯(lián)網(wǎng)、IT業(yè)界、通信、趨勢(shì)、科技訪談等。
下面以 網(wǎng)易科技-智能 首頁(yè)為例,爬取文章的【鏈接–標(biāo)題–發(fā)布時(shí)間–作者來源–具體內(nèi)容】等信息并存入MySQL:
網(wǎng)頁(yè)分析
按【F12】鍵進(jìn)入谷歌瀏覽器開發(fā)者工具,查看 Network – All:
點(diǎn)擊【加載更多】按鈕則出現(xiàn)第二個(gè) smart_datalist.js ,對(duì)比觀察 URL 的不同可直接構(gòu)造用于翻頁(yè)。
smart_datalist.js 中的內(nèi)容包含 json 格式的數(shù)據(jù):
后續(xù)再逐一訪問每篇文章的 docurl ,獲取全文即可。
安裝配置 MySQL
網(wǎng)上教程很多,請(qǐng)自行百度或Google。
完整代碼
#!/usr/bin/env python # -*- coding: utf-8 -*-""" 爬取【網(wǎng)易科技-智能】頻道首頁(yè)的【今日熱點(diǎn)】文章,并存入MySQL數(shù)據(jù)庫(kù) @Update: 2019-03-20 @Author: Newyee @Python: 3.6.5 @MySQL : 8.0 """import requests from lxml import etree import re import time import pymysqlheaders = {'User-Agent': 'Mozilla/5.0 (Windows x86; rv:19.0) Gecko/20100101 Firefox/19.0'} pattern = re.compile(r' {20}(原標(biāo)題.*)\n {16}') # 用于刪除文章開頭的“原標(biāo)題”內(nèi)容def get_html(url):try:r = requests.get(url, headers=headers)r.raise_for_status()r.encoding = r.apparent_encodingreturn r.textexcept Exception as e:print(e)return 'Error'def get_content(doc_url):try:text = get_html(doc_url)html = etree.HTML(text)contents = html.xpath('//div[@class="post_text"]//p/text()')content = ''.join(contents)content = re.sub(pattern, '', content)return contentexcept Exception as e:print('Get content Error:', doc_url, e)def main(urls):# 打開數(shù)據(jù)庫(kù)連接(具體配置信息請(qǐng)自行替換)db = pymysql.Connect(host = 'localhost',port = 3306,user = 'root',password = 'root',db = 'test',charset = 'utf8')# 建表語句sql_create = "CREATE TABLE IF NOT EXISTS wangyi_tech (id INT(5) NOT NULL AUTO_INCREMENT," \"url VARCHAR(265),title VARCHAR(265),time VARCHAR(265),source VARCHAR(265),content VARCHAR(10240),"\"PRIMARY KEY (id) ) DEFAULT CHARSET=utf8"# 創(chuàng)建一個(gè)游標(biāo)對(duì)象cursor = db.cursor()# 執(zhí)行 SQL 建表語句cursor.execute(sql_create)count = 1for url in urls:print(url)text = get_html(url)results = eval(text.replace('data_callback(', '')[:-1])for result in results:doc_url = result['docurl']title = result['title']post_time = result['time']source = result['label'].strip()try:content = get_content(doc_url)except:continueprint(count, doc_url, title)# 插入語句sql = "INSERT INTO wangyi_tech (url,title,time,source,content) " \"VALUES ('%s','%s','%s','%s','%s')" % (doc_url, title, post_time, source, content)try:# 執(zhí)行 SQL 插入語句cursor.execute(sql.replace('\n','\t'))except:print('Insert Error:', doc_url)# 如果發(fā)生錯(cuò)誤則回滾db.rollback()# 提交到數(shù)據(jù)庫(kù)執(zhí)行db.commit()count += 1time.sleep(1)time.sleep(2)# 關(guān)閉數(shù)據(jù)庫(kù)連接db.close()print('done')if __name__ == '__main__':url1 = ['http://tech.163.com/special/00097UHL/smart_datalist.js?callback=data_callback']urls = url1 + ['http://tech.163.com/special/00097UHL/smart_datalist_0{}.js?callback=data_callback'.format(str(n))for n in range(2, 10)]main(urls)運(yùn)行結(jié)果
數(shù)據(jù)示例
ps. get_content(doc_url) 獲取文章全文對(duì)部分文章可能不適用或只獲取到部分內(nèi)容
(猜測(cè)可能是因?yàn)榫W(wǎng)易的頻道或文章時(shí)間跨度比較大,網(wǎng)頁(yè)結(jié)構(gòu)不統(tǒng)一)
行文倉(cāng)促,注釋和講解部分不夠詳盡,如有疑問歡迎留言交流討論~~~
總結(jié)
以上是生活随笔為你收集整理的网易Python爬虫:爬取网易科技频道文章存入MySQL数据库的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何避免软件行业的薪资天花板?
- 下一篇: asp存入当前时间mysql_asp当前