首页 / 爬虫 / Python网络爬虫
Python网络爬虫
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python网络爬虫,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2007字,纯文字阅读大概需要3分钟。
内容图文
![Python网络爬虫](/upload/InfoBanner/zyjiaocheng/840/3b1e3856b40b430c81d97bce3009a7e2.jpg)
import requests
from bs4 import BeautifulSoup
from datetime import datetime
import re
import json
import pandas
import sqlite3
commenturl = 'http://comment5.news.sina.com.cn/page/info?\version=1&format=js&channel=gn&newsid=comos-{}&\group=&compress=0&ie=utf-8&oe=utf-8&page=1&\page_size=20'
#获取评论数量
def getCommentCounts(newsurl):
m = re.search('doc-i(.*).shtml', newsurl)
newsid = m.group(1)
comments = requests.get(commenturl.format(newsid))
jd = json.loads(comments.text.strip('var data='))
return jd['result']['count']['total']
#获取新闻详情
def getNewsDetail(newsurl):
result = {}
res = requests.get(newsurl)
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text, 'html.parser')
result['title'] = soup.select('#artibodyTitle')[0].text
result['newssource'] = soup.select('.time-source span a')[0].text
timesource = soup.select('.time-source')[0].contents[0].strip()
result['dt'] = datetime.strptime(timesource,'%Y年%m月%d日%H:%M')
result['article'] = '@'.join([p.text.strip() for p in soup.select('#artibody p')[:-1]])
result['editor'] = soup.select('.article-editor')[0].text.strip('责任编辑:')
result['comments'] = getCommentCounts(newsurl)
return result
#解析分页连接
def parseListLinks(url):
newsdetails = []
res = requests.get(url)
jd = json.loads(res.text.rstrip(');').lstrip(' newsloadercallback('))
for ent in jd['result']['data']:
newsdetails.append(getNewsDetail(ent['url']))
return newsdetails
#url为分页链接,关键参数page
url = 'http://api.roll.news.sina.com.cn/zt_list?channel=news&cat_1=gnxw&cat_2==gdxw1||=gatxw||=zs-pl||=mtjj&level==1||=2&show_ext=1&show_all=1&show_num=22&tag=1&format=json&page={}&callback=newsloadercallback&_=1509779364426'
news_total = []
#抓取1,2两页新闻信息
for i in range(1,3):
newsurl = url.format(i)
newsary = parseListLinks(newsurl)
news_total.extend(newsary)
#使用sqlite存储数据,pandas清晰展示数据
df = pandas.DataFrame(news_total)
with sqlite3.connect('news.sqlite') as db:
df2 = pandas.read_sql_query('select * from news', con = db)
df2
内容总结
以上是互联网集市为您收集整理的Python网络爬虫全部内容,希望文章能够帮你解决Python网络爬虫所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。