题目:使用标准库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 = 'D:/pic/'
xm = "赵琦"
for index,item in enumerate(result):
urls = "http://news.pdsu.edu.cn/" + item
with urlopen(str(urls)) as fp:
with open(path+xm+"_"+str(index+1)+".jpg","wb") as fp1:
fp1.write(fp.read())
第一道题没什么需要强调的,urllib是标准库,无需安装。
运行结果:
2、采用scrapy爬虫框架,抓取平顶山学院新闻网(http://news.pdsu.edu.cn/)站上的内容,具体要求:抓取新闻栏目,将结果写入lm.txt。
首先我们需要安装scrapy库,打开cmd运行pip install scrapy
(我是直接把BeautifulSoup和requests库都装了,方法与上述一样)
步骤:运行cmd开始创建项目,可以自己指定路径后再创建我这里放在了D盘(如图)
创建项目:scrapy startproject 项目名
scrapy startproject MyTest
创建爬虫名:scrapy genspider 爬虫名 允许爬取的范围
创建好之后建议先不要关闭cmd。
如:scrapy genspider xiaoshuo bbs.tianya.cn/post-16-1126849-1.shtml
按照刚才所创建的目录(路径)找到打开(我这里是D:\Python36\MyTest\MyTest\spiders)
打开后,编辑如下代码:
# -*- coding: utf-8 -*-
import scrapy
import re
from bs4 import BeautifulSoup
class MywarmSpider(scrapy.Spider):
name = 'mywarm'
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('D:\\lm.txt',"a+") as fp:
fp.writelines(content)
可以自己修改爬取到的数据所要保存的位置(我的是d:\lm.txt)
如果将上述代码复制后报如下错误:
可关闭pycharm,安装response(pip install response)
将上述操作重新来一遍。
编辑好之后继续在cmd执行 scrapy crawl 爬虫名
运行结果:
3、采用request爬虫模块,抓取平顶山学院网络教学平台上的Python语言及应用课程上的每一章标题(http://mooc1.chaoxing.com/course/206046270.html)。
首先cmd运行
创建项目名: scrapy startproject yy (yy为项目名)
创建爬虫名:scrapy genspider zq news.mooc1.chaoxing.com/course/206046270.html
(
zq为爬虫名称,mooc1.chaoxing.com/course/206046270.html为爬取起始位置)
分析:
编写正确的正则表达式筛选信息
由关键信息:<div class="f16 chapterText">第一章 python概述</div>
筛选其正则表达式如下:soup.findAll('div',class_='f16 chapterText')
找到zq.py
也就是上面创建的爬虫文件
编辑:将下面代码负责粘贴下
import requests
import bs4
import re
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 = bs4.BeautifulSoup(response,'html.parser')
t=soup.findAll('div',class_='f16 chapterText')
for ml in t:
print (ml.text)
运行结果: