import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()
etree.html可以解析html文件:
page = etree.HTML(html.lower().decode('utf-8'))
hrefs = page.xpath(u"//a")
for href in hrefs:
print href.attrib
你好!
可以通过lxml来获取指定标签的内容。
#安装lxmlpip install lxml
import requests
from lxml import html
def getHTMLText(url):
....
etree = html.etree
root = etree.HTML(getHTMLText(url))
#这里得到一个表格内tr的集合
trArr = root.xpath("//div[@class='news-text']/table/tbody/tr")
#循环显示tr里面的内容
for tr in trArr:
rank = tr.xpath("./td[1]/text()")[0]
name = tr.xpath("./td[2]/div/text()")[0]
prov = tr.xpath("./td[3]/text()")[0]
strLen = 22-len(name.encode('GBK'))+len(name)
print('排名:{:<3}, 学校名称:{:<{}}\t, 省份:{}'.format(rank,name,strLen,prov))
希望对你有帮助!