Python 抓取表格,如何根据原始输入获取td级数据
这里的注释显示了我在获取数据之前尝试过的不同事情。在wiki表中,我们有国家名称和具体国家代码等数据,我想根据用户输入获取国家代码。这将接受用户输入,询问他们要查找代码的国家,然后返回3位代码。如果您输入它找不到的内容,它将不返回任何内容Python 抓取表格,如何根据原始输入获取td级数据,python,python-2.7,web-scraping,beautifulsoup,html-table,Python,Python 2.7,Web Scraping,Beautifulsoup,Html Table,这里的注释显示了我在获取数据之前尝试过的不同事情。在wiki表中,我们有国家名称和具体国家代码等数据,我想根据用户输入获取国家代码。这将接受用户输入,询问他们要查找代码的国家,然后返回3位代码。如果您输入它找不到的内容,它将不返回任何内容 from bs4 import BeautifulSoup import urllib2 url = "en.wikipedia.org/wiki/ISO_3166-1" r = urllib2.urlopen("http://" +url) soup =
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
使用HTMLPasser,您可以从HTML页面获得任何想要的内容。这是你的答案
import requests
from bs4 import BeautifulSoup
session = requests.session()
def fetchCode(country):
page = session.get('http://en.wikipedia.org/wiki/ISO_3166-1')
soup = BeautifulSoup(page.text).find('table', {'class': 'wikitable'})
tablerows = soup.findAll('tr')
for tr in tablerows:
td = tr.findAll('td')
if td:
if td[0].text.lower() == country.lower():
return td[3].text
print fetchCode(raw_input('Enter Country Name:'))
你必须使用bs4吗?我认为这可以通过简单的HTML解析器来完成。澄清一下,您是否正在尝试制作一个程序,有人可以键入其中一个国家的名称,它将返回从该页面获取的国家代码?使用Wikipedia获取您可能已经在本地文件中的资源是。。。很有意思。谢谢你,它成功了,但是我还需要做一些其他的事情,如果我得不到它的价值,我会在这个问题上回复你
from HTMLParser import HTMLParser
import requests
import re
class MyHTMLParser(HTMLParser):
data = []
def handle_data(self, data):
if re.findall('[a-zA-Z-:]', data):
self.data.append(data)
if __name__ == '__main__':
url = 'http://en.wikipedia.org/wiki/ISO_3166-1'
rsp = requests.get(url)
p = MyHTMLParser()
p.feed(rsp.text)
s = p.data[p.data.index('Afghanistan'):p.data.index('ISO 3166-2:ZW')+1]
name = raw_input('please input country name: ')
print s[s.index(name)+3]