【问题标题】:Scraping a table, how to fetch td level data based on raw_input刮表,如何根据raw_input获取td级别的数据
【发布时间】: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


【解决方案1】:

这需要用户输入,询问他们要查找代码的国家/地区,然后返回 3 位数代码。如果你输入了它找不到的东西,它不会返回任何东西。

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:'))

【讨论】:

  • 谢谢它的工作,但我必须在它上面做更多的事情,如果我没有得到价值将在这个上回复你
【解决方案2】:

使用 HTMLParser,你可以从 HTML 页面中得到任何你想要的东西。这是你的答案。

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] 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-15
    相关资源
    最近更新 更多