爬取新浪新闻牛刀小试

文章目录


前言

爬虫流程

  • 获得请求地址
  • python发送请求request
  • 服务器返回响应response
#导入第三方发送请求的库,并用get方法发送请求
import requests
#爬虫地址
url="""https://mil.news.sina.com.cn/world/2023-04-20/doc-imyqzkcr5138902.shtml"""
res = requests.get(url=url)   #发送get请求
res.encoding = res.apparent_encoding   #编码方式按照自动识别的编码方式编码,或者直接设置成“utf8”
#解析网页的第三方库:pip install beautifulsoup4
from bs4 import BeautifulSoup
#解析返回数据的文本
soup = BeautifulSoup(markup=res.text)
soup.find(name="div",attrs={"class":"article"}).text
wrapper = soup.find(name="div",attrs={"class":"article"})
#爬虫数据保存到本地
with open("paragraph.txt",mode ='w',encoding="utf8") as f:
    for paragraph in wrapper.find_all(name = 'p'):
        print(paragraph.text,file = f)
#         f.write(paragraph)
#         f.write("\n")
        print(file=f)
#爬取文章标题
# wrapper.find_all(name = 'p')
title = soup.find(name="div",attrs={"class":"main-content w1240"}).find_all(name="h1")[1].text
#爬取文章中的图片数据
url = "https:"+soup.find_all(name="div",attrs={"class":"img_wrapper"})[0].find(name="img").get("src")
res1 = requests.get(url = url)
#保存图像数据到本地
with open('abc.png',mode = 'wb') as f:
    f.write(res1.content)
]
url = "https://mil.news.sina.com.cn/roll/index.d.html?cid=57919&page=5"  #一页的url
"""
    分页操作
"""
for page_no in range(1,6):
    url = "https://mil.news.sina.com.cn/roll/index.d.html?cid=57919&page={}".format(page_no)
    print(url)
"""
    列表页操作
"""
url = """https://mil.news.sina.com.cn/roll/index.d.html?cid=57919&page=1"""
res =requests.get(url=url)
res.encoding = "utf8"
soup =BeautifulSoup(markup=res.text)
li = soup.find(name="div",attrs = {"class":"fixList"}).find_all(name='a')
]
for ti in li:
    print(ti.get("href"))
  • 10
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Femme_DL

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值