Python爬虫综合实验

代码部分是老师程序,主要说明操作流程及相关库安装。

本人理解力有限,在操作执行过程也花了一些时间,所以来分享下操作流程
一、本次实验所用库有urllib、requests、beautifulsoup4、scrapy。其中urllib不用安装,其余均需安装。
安装方法:
pip install 库名 -i https://pypi.tuna.tsinghua.edu.cn/simple(换源安装会快一些,这里是清华大学的源地址)
二、实验题目
1、使用标准库urllib爬取“http://news.pdsu.edu.cn/info/1005/31269.htm”平顶山学院新闻网上的图片,要求:保存到F盘pic目录中,文件名称命名规则为“本人姓名”+ “_图片编号”,如姓名为张三的第一张图片命名为“张三_1.jpg”。

from re import findall
from urllib.request import urlopen
url = 'http://news.pdsu.edu.cn/info/1005/31269.htm'
with urlopen(url) as fp:
    content=fp.read().decode('utf-8')
pattern = '<img width="500" src="(.+?)"'
result = findall(pattern, content)  
path='E:/picture/葉某人_'
for index, item in enumerate(result):
    with urlopen( 'http://news.pdsu.edu.cn'+str(item)) as fp:
        with open(path+str(index+1)+'.jpg','wb') as fp1:
            fp1.write(fp.read())

2、采用scrapy爬虫框架,抓取平顶山学院新闻网(http://news.pdsu.edu.cn/)站上的内容,具体要求:抓取新闻栏目,将结果写入lm.txt

# -*- coding: utf-8 -*-
import scrapy
import re
from bs4 import BeautifulSoup
class MyprogramSpider(scrapy.Spider):
    name = 'myprogram'
    allowed_domains = ['pdsu.edu.cn']
    start_urls = ['http://news.pdsu.edu.cn/']
    
    def parse(self, response):
        html_doc=response.text
        soup= BeautifulSoup(html_doc, 'html.parser')         
        re=soup.find_all('h2', class_='fl')
        content=''
        for lm in re:
            print(lm.text)
            content+=lm.text+'\n'
        with open(r'E:\lm.txt', 'a+') as fp:
           fp.writelines(content)     

上面的程序是我自己的scrapy体系结构下的爬虫程序。现在说明一下操作步骤
1)创建scrapy项目(在cmd命令串口输入以下指令,初步生成相应目录和文件,默认在c盘根目录,结果如下图)
命令:scrapy startproject +<项目名字>
示例:scrapy startproject MyText2
在这里插入图片描述
2)创建爬虫
命令:scrapy genspider +<爬虫名字> + <允许爬取的域名>
示例:步骤1:cd MyText2;步骤2:scrapy genspider mywarm pdsu.edu.cn
域名目前可以直接定义,后期还需更改。结果如下图1,其中自己的爬虫程序在生成目录的spiders文件夹下,以下是我自己的路径(C:\Users\Administrator\MyText\MyText\spiders)在自己相应的爬虫名内添加如上代码,前提是安装所需库,填充完毕,我是先执行了一下程序才进行下一步的
图1

3)在命令提示符环境中执行下面的命令,运行爬虫程序。
命令:scrapy crawl 爬虫名
示例:scrapy crawl myprogram2
因为是执行程序此处不在截图,执行结果如下图
在这里插入图片描述
3、采用request爬虫模块,抓取平顶山学院网络教学平台上的Python语言及应用课程上的每一章标题,(http://mooc1.chaoxing.com/course/206046270.html)。

import requests
from bs4 import BeautifulSoup
headers = {
    'user-agent': 'Mozilla/5.0(Windows NT 10.0; WOW64)AppleWebKit/537.36 (KHTML, like Gecko)Chrome/65.0.3325.146 Safari/537.36'   
}

url = 'http://mooc1.chaoxing.com/course/206046270.html'
response = requests.get(url,headers=headers).text
soup = BeautifulSoup(response,'html.parser')
t=soup.findAll('div',class_='f16 chapterText')
for ml in t:
    print (ml.text)

在这里插入图片描述

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值