python --爬虫爬取学校官网新闻并下载到本地

IDE:jupyter Notebook
python version:python 3.6

目标数据:学校官网新闻(一页)
网址:*

使用到的库:requests urllib re BeautifulSoup os parse
( 我使用的是Anaconda3,所以一般常用的库都不需要额外来安装 )
( 如需安装:pip install <库名> )

思路:

1,获取目标网站源代码
2,从源代码中获取新闻超链接
3,通过新闻超链接获取内文
4,保存到本地*

开工

import requests
import urllib
import re
import os
from bs4 import BeautifulSoup
from urllib import parse

#1.获取网站源代码
respones = requests.get('http://**********/')
respones.encoding = 'utf-8'
html = respones.text
#获取网页源代码
#print(html)
#使用BeautifulSoup 解析网页
soup = BeautifulSoup(html,'html.parser')

#2.获取文章超链接
#req 定义匹配规则
req = r'
  • .*?.*?.*?.*?(.*?).*?.*?
  • ' #提升匹配效率 req = re.compile(req,re.S) #findall 匹配模式 result = re.findall(req,html) #使用for 循环分离新闻超链接和新闻标题 for url in result: res = (url) #不带主域名的url的连接## url = parse.urljoin(response.url,res[0]) #新闻标题 title = res[1] #print(url,title) # 3获取新闻内容 # 获取新闻内容源代码 chapt_html = requests.get(url) chapt_html.encoding = 'uft-8' html1 = chapt_html.text soup1 = BeautifulSoup(html1,'html.parser') #print(html1) #获取文章内文 content1 = soup1.select('#textbody') content = content1[0].text #print(content) #4 保存到本地 #用标题显示下载进程 print("正在下载:%s"%title) #下载新闻 #编码问题:定义目标文件的编码,使编码保持一致 f = open('{}.txt'.format(title),'w',encoding = 'utf-8') f.write(content) f.close()

    遇到的问题:

                 1.抓取新闻超链接时,得到的是不带主域名的url
    

    解决方法:

            1.导入urllib的parse
            2.调用parse.urljoin()进行拼接
            from urllib import parse
            url = parse.urljoin(response.url, get_url)
    #其中response.url会自动提取出当前页面url的主域名,get_url是从response中的元素中提取的没有主域名的url
    

    原文链接:
    爬虫——response中获取的不带主域名的url的拼接

                2.保存到本地时出现的乱码问题
    

    解决办法:

                    2.统一文件的编码
    

    原文链接:
    编码问题(原标题太长…)

    你可能感兴趣的:(python)