pycharm中python爬取知网论文信息并保存在Excel中(1)

#C:\Users\Dell\PycharmProjects\scratch_one\20200208_paper.xlsx最终输出文件的地址

import requests
from bs4 import BeautifulSoup
from openpyxl import workbook  # 写入Excel表所用
#from openpyxl import load_workbook  # 读取Excel表所用


if __name__=="__main__":
    #  创建Excel表并写入数据
    ws = []  # 全局工作表对象
    wb = workbook.Workbook()  # 创建Excel对象
    ws = wb.active  # 获取当前正在操作的表对象
    ws.append(['标题名', '链接地址', '摘要', '单位—类型—年份—下载次数-被引次数'])     # 往表中写入标题行,以列表形式写入!


    keywords=input("请输入") #查询的主题 ,引号内容根据需要修改
    target='http://search.cnki.net/search.aspx?q='+str(keywords)+'&rank=relevant&cluster=all&val=CJFDTOTAL&p={}'
    user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36'
    headers = {'User-Agent':user_agent}
    for i in range(10):
        i=i*15 #每页有15篇论文
        target=target.format(i) #翻页,是在p={}中修改页数链接
        req=requests.get(url=target)
        html=req.text
        html=html.replace('<br>',' ').replace('<br/>',' ').replace('/>','>')
        bf=BeautifulSoup(html,"html.parser")
        texts=bf.find('div',class_='articles')#查看页面对应的审查元素,标签为articles
        texts_div=texts.find_all('div',class_='wz_content')#查看页面对应的审查元素
        for item in texts_div:
            item_name=item.find('a').text #标题
            item_href=item.find('a')['href']#链接网址
            item_abstract = item.find('span', class_='text').text#摘要
            item_refer = item.find('span', class_='year-count').text#发表单位、发表类型、发表年份、下载次数_引用次数

            ws.append([item_name,item_href,item_abstract,item_refer]) #向表格中添加需要的信息

    wb.save('20200208_paper.xlsx')
    print("ok")
发布了233 篇原创文章 · 获赞 20 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_42565135/article/details/104265871