![](/img/trans.png)
[英]Reading Web Page lost some information no matter using Python or Java
[英]reading some content from a web page read in python
我正在嘗試從 web 的 python 模塊讀取一些數據。
我設法閱讀,但在解析這些數據和獲取所需信息時遇到了一些困難。
我的代碼如下。 任何幫助表示贊賞。
#!/usr/bin/python2.7 -tt
import urllib
import urllib2
def Connect2Web():
aResp = urllib2.urlopen("https://uniservices1.uobgroup.com/secure/online_rates/gold_and_silver_prices.jsp");
web_pg = aResp.read();
print web_pg
#Define a main() function that prints a litte greeting
def main():
Connect2Web()
# This is the standard boilerplate that calls the maun function.
if __name__ == '__main__':
main()
當我打印這個web 頁時,我打印了整個 web 頁。
我想從中提取一些信息(例如"SILVER PASSBOOK ACCOUNT"
並從中獲取匯率),我在解析此 html 文檔時遇到了一些困難。
不推薦使用 RE 來匹配 XML/HTML。 但是,它有時可以工作。 最好使用 HTML 解析器和 DOM API。這是一個示例:
import html5lib
import urllib2
aResp = urllib2.urlopen("https://uniservices1.uobgroup.com/secure/online_rates/gold_and_silver_prices.jsp")
t = aResp.read()
dom = html5lib.parse(t, treebuilder="dom")
trlist = dom.getElementsByTagName("tr")
print trlist[-3].childNodes[1].firstChild.childNodes[0].nodeValue
您可以遍歷trlist
來查找您感興趣的數據。
從評論中添加: html5lib
是第三方模塊。 請參閱html5lib 站點。 easy_install
或pip
程序應該能夠安裝它。
可以使用正則表達式來獲取所需的數據:
import urllib
import urllib2
import re
def Connect2Web():
aResp = urllib2.urlopen("https://uniservices1.uobgroup.com/secure/online_rates/gold_and_silver_prices.jsp");
web_pg = aResp.read();
pattern = "<td><b>SILVER PASSBOOK ACCOUNT</b></td>" + "<td>(.*)</td>" * 4
m = re.search(pattern, web_pg)
if m:
print "SILVER PASSBOOK ACCOUNT:"
print "\tCurrency:", m.group(1)
print "\tUnit:", m.group(2)
print "\tBank Sells:", m.group(3)
print "\tBank Buys:", m.group(4)
else:
print "Nothing found"
如果您在循環中進行匹配,請不要忘記重新re.compile
模式。
您也可以嘗試Grablib 。 和/或您可以使用 XPath(帶/不帶 Grab)。 以后可能對你有用,這里有一些例子:
g = Grab()
g.go(address)
user_div = g.xpath('//*/div[@class="user_profile"]') # main <div> for parse
country = user_div.find('*/*/a[@class="country-name"]')
region = user_div.find('*/*/a[@class="region"]') # look for <a class="region">
city = user_div.find('*/*/a[@class="city"]')
friends = [ i.text_content() for i in user_div.findall('dl[@class="friends_list"]/dd/ul/li/a[@rel="friend"]') ]
# and another ability, i.e. you have 2 tags:
# <tr> <td>Text to grab</td> <td>if only that tag contains this text</td> </tr>
val = user_div.xpath(u"dl/dt[contains(text(),'%s')]/../dd/text()" % 'if only that tag contains this text')
# print val[0] <- will contain 'Text to grab'
祝你好運。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.