web crawling(plus5) news crawling and proxy

本文介绍了一种使用 Python 的 urllib 库来爬取新浪新闻首页所有新闻链接的方法,并保存这些链接指向的网页内容。此外,还展示了如何利用代理服务器进行网页抓取。

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

#Author:Mini
#!/usr/bin/env python
import urllib.request
import urllib.error
import re
data=urllib.request.urlopen("http://news.sina.com.cn/").read()
data1=data.decode("utf-8","ignore")
pat=' href="(http://news.sina.com.cn/.*?)">'
allurl=re.compile(pat).findall(data1)
for i in range(0,len(allurl)):
try:
print(str(i)+"\n\ntime")
thisurl=allurl[i]
fh="E:/m/"+str(i)+".html"
urllib.request.urlretrieve(thisurl,fh)
print("success!")
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
import urllib.error

def use_proxy(url,proxy_addr):
proxy=urllib.request.ProxyHandler({"http":proxy_addr})
opener1=urllib.request.build_opener(proxy,urllib.request.HTTPHandler)
urllib.request.install_opener(opener1)
proxy_addr="220.161.37.21:8118"
url="http://blog.youkuaiyun.com/"
headers=("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36Query String Parametersview sourceview URL encoded")
opener=urllib.request.build_opener()
opener.addheaders=[headers]
urllib.request.install_opener(opener)
data=use_proxy(url,proxy_addr)
data=urllib.request.urlopen(url).read().decode("utf-8","ignore")
print(len(data))

pat=' <h3 class="csdn-tracking-statistics" data-mod="popu_430" data-poputype="feed" data-feed-show="false" data-dsm="post"><a href="(.*?)"'
res=re.compile(pat).findall(data)
for i in range(0,len(res)):
try:
fil="E:/m/"+str(i)+".html"
urllib.request.urlretrieve(res,filename=fil)
print(str(i),"\n\ntime")
except urllib.error.URLError as e:
if hasattr(e, "code"):
print(e.code)
if hasattr(e, "reason"):
print(e.reason)

转载于:https://www.cnblogs.com/rabbittail/p/7623041.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值