如何阅读网站的内容?

时间:2016-03-19 14:19:22

标签: python json beautifulsoup web-crawler urllib

我是使用python 2.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)   

结果显示如下:

> ValueError: No JSON object could be decoded    

因此,我将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

2 个答案:

答案 0 :(得分:3)

如果您对空气质量指数感兴趣,请找div aqivalue级:

>>> 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'

答案 1 :(得分:2)

第一个网址http://aqicn.org/city/shenyang/usconsulate/json实际上不会返回JSON数据。它返回HTML数据。如果您对此内容真的很感兴趣,则必须解析HTML数据。

您可以使用Beautifulsoup's HTML parser执行此操作,但lxml.html包稍微简单一点。