本文摘自php中文网,作者零到壹度,侵删。
本次的这篇文章主要是和大家分享了一篇关于记录一次简单的Python爬虫实例 ,有需要的小伙伴可以看一下。主要流程分为:
爬取、整理、存储
1.其中用到几个包,包括
requests 用于向网站发送请求,并获得网页代码
BeautifulSoup4 用于处理获得的网页代码,提取有效信息
pandas 用于存储信息
其中在to_excel(‘docname.xlsx’)时,可能去要另外的包 openpyxl
1 2 3 4 5 6 7 8 | import requests
from bs4 import BeautifulSoup
import re
import json
import pandas
import excel
import sqlite3
# import openpyxl
|
2.以爬取新浪网址中各个新闻的责任编辑为例子
可以按照倒推的方式确定def的functions
获取到了当条新闻下的网页网址后,如何获得责任编辑?
d
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | ef getComments(url):
# 向url对应网址发送请求,获取到的网页内容存储在res中
res=requests.get(url)
# 将res内容编码,编码的方式 'utf-8' 根据网页的charset而定
res.encoding= 'utf-8'
# 因为需要处理res,因此将文本存入soup
# html.parser不清楚是干嘛的
soup=BeautifulSoup(res.text, 'html.parser' )
# 根据所需要的内容,通过BS4的select选择,得到数组,用[0]取出元素
# 因为是文本所以直接通过.text得到所需要的内容
return soup.select( '.show_author' )[0].text
# 在soup.select( '.link' )[0]中,若为id则带#
# 若为 class 则带.
# 其他的如a和h1等则无要求
#其中需要层层select并取[0]
#有些有多元素,则需通过 for 遍历
|
ii) 根据主页面如何获得各条新闻网页的网址
某行文件是在json中发现,因此通过comments=requests.get(‘url’)再
jd=json.loads(comments.text.strip(‘var data=‘))
jd=[‘result’][‘count’][‘total’] ==>这里为字典中的字典,可以从网页检查元素的preview中查看
==>可转化为字典
其中要恢复成字典,左右两头多出了什么就要通过strip()去除
有些需要分左右侧分别删除则通过lstrip()与rstrip(),即left和right
==>for ent in ~:
ent[‘url’]
***) soup.select()到的所需元素在同一个类中,则可以使用contents[0]区分
***)time与str间的转换
1 2 3 | from datetime import date time
Str==>time dt=datetime. strptime (timesource,’%Y%m%d’)
time==>Str dt. strftime (‘%Y-%m-%d’)
|
***) 将list[]各元素连接
1 2 | ‘-‘.join(list) #将list中的各元素以-方式连接
‘’.join([p.text.strip() for p in soup.select(‘#artibody p’)[:-1]])
|
***) 对于有多页的网址,则需要找到page对应部分改为{},
然后通过format()进行替换
1 2 3 4 5 | news_total=[]
for i in range(1,3):
newsurl=url.format(i)
newsary=parseListlink(newsurl)
new_total.extend(newsary)
|
3. 使用pandas存储数据,其中是DataFrame()功能函数
1 2 3 | df=pandas.DataFrame(list)
print (df.head(20)) #显示前20条信息
df.to_excel( 'news.xlsx' ) #转存为excel格式,名字为news.xlsx
|
其中list的格式为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | for u in geturl(url):
excel1 = [] # 循环开始清空数组
result = {} # 循环开始清空字典
try :
# 每个条目在新字典赋值
result[ 'zeren' ]=getComments(u)
result[ 'id' ]=i
i=i+1
except:
continue
#每个条目形成数组
excel1.append(result)
#在列表中添加数组
list.extend(excel1)
|
4. 存储数据库
1 2 3 4 5 6 7 8 | df=pandas.DataFrame(list)
print (df.head(20)) #显示前20条信息
# df.to_excel( 'news.xlsx' ) #转存为excel格式,名字为news.xlsx
with sqlite3.connect( 'news.sqlite' ) as db:
# 存入news.sqlite文件中的news表格
df.to_sql( 'news' ,con=db)
# 读取/查询news表格并将数据赋值给df2
df2=pandas.read_sql_query( 'SELECT * FROM news' ,con=db)
|
以上就是记录一次简单的Python爬虫实例的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
怎么通过Python挣外快
Python怎么读写excel
Python怎么用pip安装库
Python实现各种最优化算法
Python 中的selenium异常处理
如何在Python中使用json数据?(代码示例)
Python如何使用正则表达式排除集合中字符的功能详解
Python实现有序字典方法示例
Python学习路线图的总结
9种Python web程序的部署方式小结
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » 记录一次简单的Python爬虫实例