2012-12-20 242 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頁面很有用。它提供瞭如何從網頁中提取數據的完整示例。