使用beautifulsoupfind方法从选项卡获取数据

2024-09-28 05:26:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个Python脚本,使用BeautifulSoup从这个网页中获取值:https://uk-air.defra.gov.uk/latest/currentlevels

我想用汤。找()从“监测地点”为“爱丁堡圣伦纳德”的表格行中获取“每小时平均二氧化氮”和“上次更新”的值。在

由于我是新的网络抓取,我有一点麻烦,所以将感谢任何帮助在这方面。在


Tags: https网络脚本网页airlatest表格gov
3条回答

废弃表列表中的所有html表。 表索引可能会更改,因此不应依赖行/列索引。 下面脚本的一部分查找搜索到的数据的索引。此外,它打印头名称:所以您知道want是您获得的数据。在

from bs4 import BeautifulSoup
import urllib.request
import re

with urllib.request.urlopen('https://uk-air.defra.gov.uk/latest/currentlevels?view=region') as response:
   htmlData = response.read()
soup = BeautifulSoup(htmlData, 'html5lib')

tables = soup.find_all('table', attrs={'class':'current_levels_table'})

#what you want to check:
Iwant = ['nitrogen', 'update']
about = 'Edinburgh'
for table in tables:
    #get header to have the data (we're looking for) column number and table real names
    table_head = table.find('thead')
    headrows = table_head.find_all('tr')
    measures = headrows[1].find_all('th')
    for colnum, measure in enumerate(measures):
        index.update({colnum: measure.text.strip() for wanted in Iwant if re.search(wanted+'(?iu)', measure.text)})
    #get table content and look for Edinburgh
    table_body = table.find('tbody')
    rows = table_body.find_all('tr')
    for row in rows:
        cels = row.find_all('td')
        rowContent = [cel.text.strip().replace(u'\xa0', u' ').replace(u'\n        Timeseries Graph', u'') for cel in cels if cel]
        if re.search(about+'(?iu)', rowContent[0]):
            for indexwanted, measurewanted in index.items():
                print(measurewanted, ':', rowContent[indexwanted])

利用d2718nis的建议,您可以这样做。当然,很多其他的方法也可以。在

首先,找到包含“爱丁堡圣伦纳德”文本的链接。然后找到那个link元素的grand父元素,它是一个tr元素。现在确定tr中的td元素。当您检查表时,您会看到您想要的列是第4列和第7列。从所有td元素中获取这些元素作为(0-相对)第3和第6个。最后,展示这些元素的原始文本。在

您需要做一些聪明的事情来从这些结果中提取正确可读的字符串。在

>>> import requests
>>> import bs4
>>> page = requests.get('https://uk-air.defra.gov.uk/latest/currentlevels', headers={'User-Agent': 'Not blank'}).content
>>> soup = bs4.BeautifulSoup(page, 'lxml')
>>> Edinburgh_link = soup.find_all('a',string='Edinburgh St Leonards')[0]
>>> Edinburgh_link 
<a href="../networks/site-info?site_id=ED3">Edinburgh St Leonards</a>
>>> Edinburgh_row = Edinburgh_link.findParent('td').findParent('tr')
>>> Edinburgh_columns = Edinburgh_row.findAll('td')
>>> Edinburgh_columns[3]
<td class="center"><span class="bg_low1 bold">20 (1 Low)</span></td>
>>> Edinburgh_columns[6]
<td>05/08/2017<br/>14:00:00</td>
>>> Edinburgh_columns[3].text
'20\xa0(1\xa0Low)'
>>> Edinburgh_columns[6].text
'05/08/201714:00:00'

你可以从这个开始:

import requests
from bs4 import BeautifulSoup


# Request the page, set headers to prevent 403 Forbidden
page = requests.get(
    url='https://uk-air.defra.gov.uk/latest/currentlevels',
    headers={'User-Agent': 'Not blank'})
# Get html from page
html = page.text
# BeautifulSoup object
soup = BeautifulSoup(html, 'html5lib')

for table in soup.find_all('table'):
    # Print all tables on the page
    print(table)

相关问题 更多 >

    热门问题