如何阅读网站内容?

2024-09-30 16:20:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我是使用Python2.7的网络爬虫新手。在

1。背景

现在,我想从AQICN.org收集有用的数据,这是一个提供全世界空气质量数据的好网站。在

我想用python每小时获取所有中国网站的数据。但我现在卡住了。在

2。我的麻烦

以这个网站(http://aqicn.org/city/shenyang/usconsulate/)为例。在

本页提供美国驻华领事馆的空气污染和气象参数。使用这样的代码,我无法获得有用的信息。在

import urllib
from bs4 import BeautifulSoup
import re
import json

html_aqi =    
urllib.urlopen("http://aqicn.org/city/shenyang/usconsulate/json").read().decode('utf-8')
soup= BeautifulSoup(html_aqi)
l = soup.p.get_text() 
aqi= json.loads(l)   

结果如下:

^{pr2}$

因此,我将html_aqi更改为以下格式(引用某人的工作):

http://aqicn.org/aqicn/json/android/shenyang/usconsulate/json

代码运行良好。在

3。我的目标。

格式1:(http://aqicn.org/city/shenyang/usconsulate/json)
格式2:(http://aqicn.org/aqicn/json/android/shenyang/usconsulate/json)

一般来说,我可以处理格式2。但是,我收集了中国所有网站的格式1网站。 那么,有人能帮我处理格式1吗?谢谢。在

更新

格式1很难转换成第二种格式(需要考虑很多条件)

使用这样的代码很难做到:

city_name = url_format1.split("/")[5]
site_name = url_format1.split("/")[6]
url_format2 = "http://aqicn.org/aqicn/json/android/"+ city_name + "/"+    site_name

### --- Reason Why it's hard  in practice  
1559 sites need to be care with, and these sites differ by their location.     
Some are in city, some are in county. Their url are not the same pattern.   
for example: 
Type1 --> http://aqicn.org/city/hebi/json
Type2 --> http://aqicn.org/city/jiangsu/huaian/json
Type3 --> http://aqicn.org/city/china/xinzhou/jiyin/json

Tags: 数据nameorgimportjsonhttpurlcity
2条回答

如果您对空气质量指数感兴趣,请找到divaqivalue等级:

>>> import urllib
>>> from bs4 import BeautifulSoup
>>> 
>>> url = "http://aqicn.org/city/shenyang/usconsulate/json"
>>> soup = BeautifulSoup(urllib.urlopen(url), "html.parser")
>>> soup.find("div", class_="aqivalue").get_text()
u'171'

第一个url http://aqicn.org/city/shenyang/usconsulate/json实际上并不返回JSON数据。它返回HTML数据。如果你真的对这些内容感兴趣,你必须解析HTML数据。在

您可以使用Beautifulsoup's HTML parser来完成此操作,尽管lxml.html包稍微简单一些。在

相关问题 更多 >