用requests和BeautifulSoup爬取静态网页
一、案例说明
本案例使用requests和BeautifulSoup爬取湖北经济学院经院要闻的前2页新闻标题、日期、发布者、内容
二、爬虫思路
首先找到网址(http://news.hbue.edu.cn/jyyw/list.htm)的页面,右键“检查”,显示出开发者模式
发现每页的新闻网址都为(http://news.hbue.edu.cn/jyyw/list+数字.htm),所以可以根据这个信息来爬取不同的新闻网页
发现每页新闻的网址都在span class="Article_Title"中,,所以可以根据这个信息来爬取不同的新闻网页信息
三、代码
import requests
from bs4 import BeautifulSoup
import csv
import pandas as pd
import re
def getnews(newurl):
html = requests.get(newurl)
bs = BeautifulSoup(html.content,'lxml')
the_title = bs.find(name='h1',class_="arti_title")
title = re.sub(' ','',the_title.string)
#用正则表达式将空格去除
publisher = bs.find(name='span',attrs={
'class':'arti_publisher'})
date = bs.find(class_="arti_update")
print(title)
print(publisher.string)
print(date.string)
#获取过滤出的节点文本内容,用.string
for i in range(1,3):
url = 'http://news.hbue.edu.cn/jyyw/list' + str(i) + '.htm'
html = requests.get(url)
#用requests的get方法
bs = BeautifulSoup(html.content,'lxml')
#需使用.content
newurlset = bs.find_all(name='span',attrs={
'class':'Article_Title'})
#BeautfiulSoup的find_all返回的是tag对象的集合,故可以用循环语句提取
for i in newurlset:
#因为有个新闻的网址链接与其他不同,故加上这个判断语句
if 'http://news.hbue.edu.cn' in i.a.attrs['href']:
newurl = i.a.attrs['href']
else:
newurl = 'http://news.hbue.edu.cn' + i.a.attrs['href']
#找到网页前缀,再提取出下一步。因为a标签为span节点的子节点,故可直接选。但只可选择至子节点。
getnews(newurl)