【问题标题】:Python Scraper - Find Data in ColumnPython Scraper - 在列中查找数据
【发布时间】:2018-06-20 03:13:31
【问题描述】:

我正在开发我的第一个网站抓取工具,并试图获取保存在网页 https://mcassessor.maricopa.gov/mcs.php?q=14014003N 列中的数字 41,110。下面是我的代码。

我怎样才能得到这个号码并打印出来?

from bs4 import BeautifulSoup
import requests
web_page = 'https://mcassessor.maricopa.gov/mcs.php?q=14014003N'
web_header = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}
response = requests.get(web_page,headers=web_header)
soup = BeautifulSoup(response.content,'html.parser')
for row in soup.findAll('table')[0].thread.tr.findAll('tr'):
    first_column = row.findAll('th')[0].contents
    print(first_column)

【问题讨论】:

    标签: html python-3.x web-scraping beautifulsoup findall


    【解决方案1】:

    一种直接的方法是获取“改进”表,获取第一个非标题行,然后获取该行中的最后一个单元格:

    table = soup.find("table", id="improvements-table")
    first_row = table.find_all("tr")[1]  # skipping a header
    last_cell = first_row.find_all("td")[-1]
    print(last_cell.get_text())  # prints 41,110
    

    更通用的方法是从这个表中创建一个字典列表,其中键是标题名称:

    table = soup.find("table", id="improvements-table")
    headers = [th.get_text() for th in table('th')]
    
    data = [dict(zip(headers, [td.get_text() for td in row('td')])) for row in table("tr")[1:]]
    print(data)
    print(data[0]['Sq Ft.'])
    

    打印:

    [
        {u'Imp #': u'000101', u'Description': u'Mini-Warehouse', u'Age': u'1', u'Rank': u'2', u'Sq Ft.': u'41,110', u'CCI': u'C', u'Model': u'386'}, 
        {u'Imp #': u'000201', u'Description': u'Site Improvements', u'Age': u'1', u'Rank': u'2', u'Sq Ft.': u'1', u'CCI': u'D', u'Model': u'163'}
    ]
    41,110
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-13
      • 2012-03-21
      相关资源
      最近更新 更多