网络爬虫基础练习

import requests

from bs4 import BeautifulSoup

newsurl='http://news.gzcc.cn/html/xiaoyuanxinwen/'

res = requests.get(newsurl) #返回response对象

res.encoding='utf-8'

soup = BeautifulSoup(res.text,'html.parser')



# 取出h1标签的文本
print(soup.h1.text)

# 取出a标签的链接
print(soup.a.attrs['href'])

# 取出所有li标签的所有内容
for i in soup.select('li'):
    print(i.contents)

# 取出第2个li标签的a标签的第3个div标签的属性
print(soup.select('li')[1].select('a')[0].select('div')[2].attrs)




# 标题
print(soup.select('.news-list-info')[0].select('span')[1].text)

# 时间
print(soup.select('.news-list-info')[0].contents[0].text)


# 来源
print(soup.select('.list-container')[0].a.get('href'))


# 链接
print(soup.select('.list-container')[0].select('a')[0].attrs['href'])

 

posted @ 2018-03-29 19:49  183区展伯  阅读(110)  评论(0编辑  收藏  举报