因为最近也在学习python,爬虫和一点pandas的内容
刚好看到一篇博客,博客地址:https://blog.csdn.net/xiaoma_2018/article/details/108231658也是实现一样的内容的,只是使用的方式被我改了一下,我也是借鉴学习大佬的方法
我所使用到的库有lxml, urllib.request
代码如下
''' 导入所需要的库 '''
import urllib.request as ur
import lxml.etree as le
import pandas as pd
from config import EachSource,OUTPUT
url = 'https://blog.csdn.net/shine_a/article/list/2'
#得到博客所有内容
def get_blog(url):
req = ur.Request(
url=url,
headers={
'cookie':'c_session_id%3D10_1600923150109.901257%3Bc_sid%3D40c3e11ae0d6021f6f8323db1cc321a1%3Bc_segment%3D9%3Bc_first_ref%3Dwww.google.com.hk%3Bc_first_page%3Dhttps%253A%2F%2Fwww.csdn.net%2F%3Bc_ref%3Dhttps%253A%2F%2Fblog.csdn.net%2F%3Bc_page_id%3Ddefault%3B',
'User_Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36'
}
)
response = ur.urlopen(req).read()
return response
# 得到每一个博客的链接, 进入二级页面并提取数据
def get_href_list():
href_s = le.HTML(response).xpath('//div[@class="articleMeList-integration"]/div[2]/div/h4/a/@href')
for data in href_s:
rp = ur.urlopen(data).read()
html = rp.decode()
title = le.HTML(html).xpath('//div[contains(@class,"main_father")]/div/main/div[1]/div/div/div/h1/text()')
readCount = le.HTML(html).xpath('//div[@class="bar-content"]/span[@class="read-count"]/text()')
time = le.HTML(html).xpath('//div[@class="article-info-box"]/div[3]/span[2]/text()')
url_href = data
content = [title[0],readCount[0],time[0],url_href]
info = ",".join(content)
# print(info)
with open(EachSource,'a',encoding='utf-8') as f:
f.writelines(info+'\n')
# 处理数据
def parseData():
f = pd.read_table('./info.txt',sep=',',header=None, names=['文章标题', '浏览量', '发布时间','文章链接'])
f.to_csv(OUTPUT)
if __name__ == '__main__':
blogID = input('Enter blogID:')
pages = input('Enter page:')
response = get_blog(
url= 'https://blog.csdn.net/{blogID}/article/list/{pages}'.format(blogID=blogID, pages=pages)
)
# data = response.decode('utf-8')
# with open('a.txt','w',encoding='utf-8') as f:
# f.write(data)
print('获取博客链接...')
get_href_list()
print("开始获取数据...")
parseData()
print("结束获取数据...")
说一下我在实现的过程中所遇到的一些问题:
1.在用xpath得到的每个博客的url的时候,我通过data遍历进入href_s但是遍历出来的是url并不是直接进入博客(二级页面了)返回的是一些xml格式的对象,所以rp = ur.urlopen(data).read(),html = rp.decode()的方式需要进入到url对象然后进行decode才能进行下面的xpath
以下是实现的情况:
过程:
最后感谢Caso_卡索博主所提供的内容提供学习与参考!