requests基本应用

import requests
from bs4 import BeautifulSoup


res=requests.get("http://war.163.com/")
res.encoding='gbk'
coding=res.encoding
cont=res.text


soup = BeautifulSoup(cont, 'html.parser')
#使用select找出含有h1标签的元素
header = soup.select('h1')
# print(header)
# # print(header[0])
# print(header[0].text)
#打印所有包含a的信息
alink = soup.select('a')
# print('所有包含超链接的信息:'+alink)
# for link in alink:
#     print(link)
#     print(link.text)


#使用select找出所有id为title的元素(id前面需要加#)
alink = soup.select('#title')
# print(alink)


# 使用select找出所有class为link的元素(class前面需要加.)
# for link in soup.select('ul.ntes-quicknav-column'):
#     print(link)


# 使用select找出所有a tag的href链接
alinks = soup.select('a')
for link in alinks:
    # 获取属性值

    print(link.get_attribute_list(key="href",default="ni")[0])

# 制作新浪新闻网络爬虫
import requests
from bs4 import BeautifulSoup
'''
res = requests.get('http://news.sina.com.cn/china')
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text, 'html.parser')


for news in soup.select('.news-item'):
    if (len(news.select('h2')) > 0):
        h2 = news.select('h2')[0].text
        time = news.select('.time')[0].text
        a = news.select('a')[0]['href']
        print(time, h2, a)
'''
# 抓取新闻内文页面
res=requests.get("http://news.sina.com.cn/c/nd/2016-08-20/doc-ifxvctcc8121090.shtml")
res.encoding='utf-8'
soup=BeautifulSoup(res.text,'html.parser')
title=soup.select('#artibodyTitle')[0].text # 抓取标题
# print(f"title:{title}")
timesource = soup.select('.time-source')[0].contents[0].strip() # 抓取时间
# print(f"时间:{timesource}")
# 时间和字符串的转化
'''
from datetime import datetime
#字符串转时间 --- strptime
dt = datetime.strptime(timesource, '%Y年%m月%d日%H:%M')
print(dt)
#时间转字符串 --- strftime
str=dt.strftime('%Y-%m-%d')
print(dt)
'''
medianame = soup.select('.time-source span a')[0].text # 抓取来源
print(medianame)


# 抓取新闻内容,并存储在列表对象中
article=[]
mlist=soup.select('#artibody p')#返回list
# 遍历该集合
#使用切片去掉编辑人
for i in mlist[:-1]:
    print(i.text)
    # 向列表对象中添加新闻内容
    article.append(i.text)

猜你喜欢

转载自blog.csdn.net/wshsdm/article/details/80616823