Python获取网页数据



我正在尝试创建一个从电视网站上获取HTML的程序当前在表中,例如:BBC 1-"程序名称"。如果有人能提供帮助,我只需要在我的第一个拆分功能之后所做的帮助。

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

我不会拆分输出,而是使用某种HTML解析器。美丽的汤是一个不错的选择。

听起来您想要屏幕刮板,而不是串起html。一个好的屏幕刮擦工具是废纸,它使用XPath检索数据。

浏览页面上的废弃很有用。它提供了一个如何从网页中提取数据的完整示例。

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

用于HTML解析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'},...

最新更新