【发布时间】:2017-02-18 17:52:50
【问题描述】:
from bs4 import BeautifulSoup
import urllib2
url = "en.wikipedia.org/wiki/ISO_3166-1"
r = urllib2.urlopen("http://" +url)
soup = BeautifulSoup(r)
#tables = soup.findAll("table")
#i want to fetch data of india and store in a variable
t = soup.find("table")
for t1 in t.find_all('tr'):
#for cell in t1.find_all('td'):
cell = t1.find_all('td')
shortname = cell[0].string
alpha2 = cell[1].a.string
#print cell.find_all(text=True)
print shortname
#cells = t.find_all('td',text="India")
#rn = cells[0].get_text()
#print cells
#soup.find_all('a')
#title = soup.a
#title
这里的 cmets 显示了我在获取数据之前尝试过的不同事情。在 wiki 表中,我们有国家名称和国家特定代码等数据,我想根据用户输入获取国家代码。
【问题讨论】:
-
一定要用bs4吗?我认为这可以通过简单的 HTML 解析器来完成。
-
澄清一下,您是否正在尝试制作一个程序,让某人可以输入其中一个国家/地区的名称并返回从该页面获取的国家/地区代码?
-
使用 Wikipedia 获取您可能已经在本地文件中拥有的资源……很有趣。
标签: python python-2.7 web-scraping beautifulsoup html-table