python简单爬虫代码示例2

目标网站:view-source:http://www.weather.com.cn/weather/101270101.shtml
代码:
from urllib.request import urlopen
from bs4 import BeautifulSoup

newshtml1=urlopen(“http://www.weather.com.cn/weather/101270101.shtml”).read() #获取二进制文件
newshtml2=newshtml1.decode(“utf-8”)#把二进制转为string类型

soup=BeautifulSoup(newshtml2,features=“lxml”)#<class ‘bs4.BeautifulSoup’>
all_ul=soup.find_all(“ul”,attrs={“class”:“t clearfix”})#<class ‘bs4.element.ResultSet’>
#print(type(all_ul[0]))#<class ‘bs4.element.Tag’>
#print(len(all_ul))
f=open(“weather.html”,“w”,encoding=‘utf-8’)
f.close()
all_li=all_ul[0].find_all(“li”)#<class ‘bs4.element.ResultSet’>
f=open(“weather.html”,“a”,encoding=‘utf-8’)
for i in all_li:
data=i.find(“h1”).get_text()
#print(type(i))#<class ‘bs4.element.Tag’>
f.write(data+"\n")
data=i.find(“p”,attrs={“class”:“wea”}).get_text()
f.write(data+"\n")
data=i.find(“p”,attrs={“class”:“tem”})
print(type(data))#<class ‘bs4.element.Tag’>
pdata1=data.find(“span”).get_text()
pdata2=data.find(“i”).get_text()
f.write(pdata1+"----"+pdata2+"\n")
data=i.find(“p”,attrs={“class”:“win”})
pdata1=data.find(“i”).get_text()
f.write(pdata1+"\n"+"\n")
f.close()
#print(len(all_li))
#for i in all_ul:

print(i)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值