Python 正则 爬新浪新闻
程序员文章站
2022-05-02 22:01:59
...
import urllib.request
import re
# 正则表达式
# aaaaa aa aab aba aabb
#a(.*?)b
data = urllib.request.urlopen("http://news.sina.com.cn/").read()
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= r"D:/Python/hoilday_codes/sina/"+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)
上一篇: Python 新浪实时新闻