运用Beautifulsoup对新闻网站进行简单的爬取

利用BeautifulSoup可以很简单的爬取网页上的内容。这个套件可以把一个网页变成DOM tree

要使用BeautifulSoup需要使用命令行进行安装,不过也可以直接用python的ide。

基础操作 :

使用之前需要先从bs4中导入包:from bs4 import BeautifulSoup

使用的代码:soup = BeautifulSoup(res.text, 'html.parser')

括号中的第一个参数中的res是源网页,res.text是源网页的html,第二个参数'html.parser'是使用html的剖析器。、

可以使用select函数找出所有含有特定标签的HTML元素,例如:soup.select('h1')可以找出所有含有h1标签得到元素

它会返回一个list,这个list包含所有含'h1'的元素.

下面就对凤凰网的一篇文章进行简单的爬取:

# coding=utf-8
from urllib import request, parse
from bs4 import BeautifulSoup
import re

#网页地址
url='http://news.ifeng.com/a/20181118/60165418_0.shtml'
#获取web网页
html=request.urlopen(url).read().decode('utf-8','ignore')
# 解析
soup=BeautifulSoup(html,'html.parser')

# 获取信息
page=soup.find('div',{'id':'artical'})
#根据所要爬取内容提取网页中的CSS元素,如标题及内容
page_topic=page.find('h1',id='artical_topic')
#使用text属性,提取标题和文本内容
topic=page_topic.get_text()
content=''
content=content+topic
page_content = page.find('div',id='main_content')
# contents=page_content.select('p')
for p in page_content.select('p'):
    content=content+p.get_text()
# print(topic)
# print('\r')
print(content)

这样就可以实现对网页新闻进行简单的爬取了


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值