python学习,新浪新闻的爬取和优快云博文爬取

本文介绍使用Python的urllib库抓取新浪新闻和优快云博客网页的具体步骤,通过正则表达式匹配目标链接并下载页面内容。详细展示了如何设置HTTP请求头,使用opener进行请求,以及如何处理URL下载过程中的错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import urllib.request
import ssl
import re#导入正则表达式模块
data=urllib.request.urlopen("http://news.sina.com.cn/").read()#将网址信息读取出来,并赋值给data
#headers=("","")#此处可以添加模拟http请求,详见前面博文
#opener...
#opener
data2=data.decode("utf-8","ignore")#编码
pat='href="(http://news.sina.com.cn/.*?)"'
allurl=re.compile(pat).findall(data2)
for i in range(0,len(allurl)):
    try:
        print("第"+str(i)+"次爬取")
        thisurl=allurl[i]
        file="E:/practice/sinanews/"+str(i)+".html"
        urllib.request.urlretrieve(thisurl,file)#下载网页
        print("---成功---")
    except urllib.error.URLError as e:
        if hasattr(e,"code"):
            print(e.code)
        if hasattr(e,"reason"):
            print(e.reason)
import urllib.request
import  re
url="http://blog.youkuaiyun.com/"
headers=("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.53 Safari/537.36")
opener=urllib.request.build_opener()
opener.addheaders=[headers]
urllib.request.install_opener(opener)
data=urllib.request.urlopen(url).read().decode("utf-8","ignore")
pat='href="(https://blog.youkuaiyun.com/.*?)"'
result=re.compile(pat).findall(data)
for i in range(0,len(result)):
    try:
        print("第"+str(i)+"次爬取")
        thisurl=result[i]
        file="E:/practice/csdntitle/"+str(i)+".html"
        urllib.request.urlretrieve(thisurl,file)
        print("成功")
    except urllib.error.URLError as e:
        if hasattr(e,"code"):
            print(e.code)
        if hasattr(e,"reason"):
            print(e.reason)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值