2012-12-20 248 views
1

我想创建一个程序,从电视上映网站获取html,然后使用拆分功能将所有html数据拆分为只有频道名称和当前正在播放的节目一个表格,例如:BBC 1 - '节目名称'。我只需要帮助我的第一次拆分功能后,如果任何人都可以帮助,将不胜感激。Python获取网页数据

import urllib2 
import string 


proxy = urllib2.ProxyHandler({"http" : "http://c99.cache.e2bn.org:8084"}) 

opener = urllib2.build_opener(proxy) 

urllib2.install_opener(opener) 

tvCatchup = urllib2.urlopen('http://www.TVcatchup.com') 

html = tvCatchup.read() 

firstSplit = html.split('<a class="enabled" href="/watch.html?c=')[1:] 
for i in firstSplit: 
    print i 

secondSplit = html.split ('1" title="BBC One"></a></li><li class="v-type" style="color:#6d6d6d;">')[1:] 

for i in secondSplit: 
print i 

回答

1

我不会拆分输出,但使用某种HTML解析器。 Beautiful Soup是个不错的选择。

-1

请不要使用urllib2。 使用请求,而不是 https://github.com/kennethreitz/requests

对于HTML解析使用BeautifulSoup http://www.crummy.com/software/BeautifulSoup/bs4/doc/

注:看来该代理下来,除去代理服务器设置,它的工作

import requests 
from BeautifulSoup import BeautifulSoup 

proxyDict = {"http":"http://c99.cache.e2bn.org:8084"} 
r = requests.get("http://www.TVcatchup.com", proxies=proxyDict) 

soup = BeautifulSoup(r.text) 
tvs = list() 

uls = soup.findAll("ul", { "class":"channels2"} 
for ul in uls: 
    div = ul.find("div") 
    if div: 
     showid = div.get("showid") 
     link = ul.find("a") 
     href = link.get("href") 
     title = link.get("title") 
     tvs.append({"showid":showid, "href":href, "title":title}) 
print tvs 

你会得到这个

[{'showid': u'450263', 'href': u'/watch.html?c=1', 'title': u'BBC One'}, 
{'showid': u'450353', 'href': u'/watch.html?c=2', 'title': u'BBC Two'}, 
{'showid': u'450398', 'href': u'/watch.html?c=3', 'title': u'ITV1'}, 
{'showid': u'450521', 'href': u'/watch.html?c=4', 'title': u'Channel 4'},... 
+0

因为这是学校工作,这是我使用这些的唯一原因,因为它们是我们在操作网页时被教导使用的。也只是为了清楚的代理处理程序是这样的程序可以在学校时通过代理实际访问互联网 – user1655562

+0

我目前正在给你写一个完整的代码,请给我一分钟:) – Goranek

+0

好的,谢谢,它只是主要我很困惑的事情是如何创建一个列表的HTML,在列表上的itter和删除其余的HTML,这就是我不知道该怎么做 – user1655562

0

这听起来像你想要一个屏幕刮板,而不是子串的HTML。一个好的屏幕抓取工具是Scrapy,它使用XPATH检索数据。

Scrapy at a glance页面很有用。它提供了如何从网页中提取数据的完整示例。