2017-10-07 54 views
-1

我正在製作遊戲,某種口袋妖怪可以去黑客攻擊。 我的遊戲必須下載設備的位置,但有一個問題。 我發現顯示您的經緯度的網站,但我無法得到它。我製作了一個腳本:在Python中獲取html網站的一部分

import urllib.request 
response = urllib.request.urlopen('http://python.org/') 
html = response.read() 
print(html) 

該腳本使站點代碼分配給名爲html的變量並將其打印出來。

(網站看起來好像是這樣)

<!DOCTYPE html> 
<html lang="en"> 
<head>...</head> 
<body style> 
<div class="container"> 
    ::before 
    <div class="rows"> 
    <div class="col-md-4 current-location-detail"> 
     <table class="table"> 
     <trbody> 
      <tr> 
      <td width="30%">Latitude </td> 
      <td id="latitude">50.19869</td> 
      </tr> 
      <tr> 
      <td>Longitude </td> 
      <td id="longitude">17.17034</td> 
      </tr> 

我怎樣才能得到經度和緯度使用此代碼?請幫幫我。

+1

你是什麼意思的「網站的一部分」?你想閱讀的HTML沒有完全下載它? (這是'urlopen'的作用),還是你想從頁面中提取一些數據? – Anonta

+0

我需要緯度 –

+0

50.19869 –

回答

1

您可以BeautifulSoup嘗試:

from urllib2 import urlopen 
from bs4 import BeautifulSoup 

response = urlopen('http://python.org/').read() 

# Create a BeautifulSoup object 
soup = BeautifulSoup(response, 'html.parser') 
soup.find("div", {"id": "success-story-2"}) 

在下面的例子中,我們收到的內容和元素ID「成功 - 故事2」。您可以使用find()find_all()來檢索您希望的文檔的各個部分。

+0

我可以在哪裏下載這些庫? –

+0

@PatrykPopowicz你不需要明確地安裝urllib2 ...它已經在那裏了......但對於BS4你可以做點安裝beautifulsoup4 –